Introduction - Java Reflection API
The Java Reflection API is a framework we can use for introspection of objects at run time. Learning about an object at run time can be very useful when writing dynamic code, programs that manipulate objects with properties unknown before runtime. We can learn of an object’s class, methods, fields, constructors, superclasses, and much more. We can create objects from classes that might not exist at compile time. Reflection can also be used extensively for debugging by changing the values of fields at run time as per our needs. Furthermore, through Reflection we can call methods that we do not know about until runtime. We can also use Reflection to manipulate arrays at runtime.
Before we continue praising Reflection’s many benefits, it is important to realize that Reflection should only be used when other methods can not do the job. Reflection is relatively slow. Reflection code is also harder to manage and maintain because of its indirect nature. For example, instead of calling a method of a particular object type (unknown), Reflection code would find the object's class type, then invoke that class type's method. Thus debugging it is harder and less efficient.
In this tutorial, we hope to provide more insight on Reflection by presenting examples that highlight the use of Reflection. We will also introduce the API and how to go about using the various files and folders. We also present arguments for and against the use of Reflection in each of the specific cases.
The following examples will provide a basic understanding of Java Reflection. Each example will discuss a different area of Reflection. Some examples build onto previous examples. Finally, it is important to reiterate that though Reflection is powerful and we can achieve greater flexibility by using it, it should not be used if non-reflective code will work as needed, mainly because of its running-time caveat.
Example 1 – Object Info – Obtaining information at runtime for a debugger.
Example 2 – Inventory – Adding objects to a list that does not exist yet
Example 3 – Book Factory – Using Proxy to trace the program
Example 4 – Class Generator – Creating classes dynamically during execution
Example 5 – Progress Checker – Running Time comparison of Reflection and non-reflection code
Example 6 – Magic Arrays – Obtaining information on Arrays
Example 7 – Array Extension – Extract elements of a certain type from an Array
Example 8 – Unique Queue – Type checking elements before adding them to an Array
Example 9 – Call Stack Introspection – Tracing the calls in the call stack