Easy Reflection using Spring ReflectionTestUtils

This post demonstrates how to get and set instance variables and invoke methods via the Reflection API using Spring ReflectionTestUtils. There are key reasons to do things via Reflection: 1) test non-public methods (not recommended, though), and 2) inaccessible instance variables (to mock).

Java Class Example

For our example, we’ll use the following simple class. Notice that internalCode is inaccessible outside of the Student class.

Testing with ReflectionTestUtils

The output is as follows.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert