![]() The problem is that you get two Base type references and you want to see if their corresponding objects are of same (sub)type and are equal.Īs solutions there is the raw solution in which you first check if the types are equal and then check all fields or you can use reflection and dynamically see if they are of the same type and iterate over all methods that start with "get" (convention over configuration), call them on both objects and call equals on the results. Invoke the Method with Reflection Finally, we call invoke on the Method object: int value ( int) indexOfMethod.invoke ( LongArrayUtil.class, someLongArray, 2L, 0, someLongArray.length) We have now successfully accessed a private method. Now we can use the invokeMethod function in ReflectionTestUtils, which uses the same algorithm as above, and saves us writing as much code: int value ReflectionTestUtils.invokeMethod ( LongArrayUtil.class, 'indexOf', someLongArray, 1L, 1, someLongArray.length) As this is a test library, we wouldn't expect to use this outside of the test code. ![]() To give an example, suppose there is a an abstract class Base which has 10 fields and has 3 subclasses SubclassA, SubclassB and SubclassC each with 10 different fields they are all simple beans. ![]() Is it a good practice to use reflection if greatly reduces the quantity of boilerplate code?īasically there is a trade-off between performance and maybe readability on one side and abstraction/automation/reduction of boilerplate code on the other side.Įdit: Here is an example of a recommended use of reflection. Android applications are written in the Java, a programming language that supports reflectionthe ability of an object to examine itself. ![]()
0 Comments
Leave a Reply. |