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 of this on objects that
your code has never even seen before.
We don’t have room here to fully cover the reflection API. 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 percent of the effort will
give you 80 percent of the fun.
The reflection API is used by JavaBeans to determine the capabilities of objects at runtime. It’s also used at a lower level 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. Your code is not allowed to do anything with the reflection API that it couldn’t do with static (ordinary, compiled) Java code. In short, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access