Reflection
In this section, we’ll take a look at the Java Reflection API,
supported by the classes in the java.lang.reflect
package. As its name suggests, reflection is the ability for a class or
object to examine itself. Reflection lets Java code look at an object
(more precisely, the class of the object) and determine its structure.
Within the limits imposed by the security manager, you can find out what
constructors, methods, and fields a class has, as well as their
attributes. You can even change the value of fields, dynamically invoke
methods, and construct new objects, much as if Java had primitive pointers
to variables and methods. And you can do all this on objects that your
code has never even seen before. The Annotations API also has the ability
to preserve metadata about source code in the compiled classes and we can
retrieve this information with the Reflection API.
We don’t have room here to cover the Reflection API fully. As you
might expect, the reflect package is
complex and rich in details. But reflection has been designed so that you
can do a lot with relatively little effort; 20% of the effort gives you
80% of the fun.
The Reflection API can be used to determine the capabilities of objects at runtime. It’s used by object serialization to tear apart and build objects for transport over streams or into persistent storage. Obviously, the power to pick apart objects and see their internals must be zealously guarded by the security manager. The general rule is that your ...