Java, Software Development, Spring

Easy Reflection using Spring ReflectionTestUtils

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

Java Class For Reflection Test

For our example, we’ll use the following simple class. Notice that the internalCode is inaccessible outside of the Student class. There is no way to access the properties except via Java Reflection API. Therefore, we could use the Reflection API in Spring, but we do not have to do it.

Nothing is preventing us from using the Reflection API. However, we may not want to create low-level (relatively speaking) codes. Instead, we can use Spring ReflectionTestUtils.

Test Reflection with Spring ReflectionTestUtils

Consider the following example codes that use Spring ReflectionTestUtils. We can use setField and getField methods to update and get property values, respectively.

Moreover, we can even call private methods using the invokeMethod method from the Spring ReflectionTestUtils. No need for Java Reflection API, right?

When we run the codes, we get the following output.

Our codes successfully updated the private field values using Spring ReflectionTestUtils. However, we do still use the Java Reflection API, but we use it indirectly because Spring ReflectionTestUtils uses the native API.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like