Java Reference
In-Depth Information
This makes reflection a very powerful technique—so it's important to understand
when we should use it, and when it's overkill.
When to Use Relection
Many, if not most Java frameworks use reflection in some capacity. Writing architec‐
tures that are flexible enough to cope with code that is unknown until runtime usu‐
ally requires reflection. For example, plug-in architectures, debuggers, code brows‐
ers and REPL-like environments are usually implemented on top of reflection.
Reflection is also widely used in testing, for example by the JUnit and TestNG libra‐
ries, and for mock object creation. If you've used any kind of Java framework then
you have almost certainly been using reflective code, even if you didn't realize it.
To start using the Reflection API in your own code, the most important thing to
realize is that it is about accessing objects where virtually no information is known,
and that the interactions can be cumbersome because of this.
g
R e l e c t i o n
d
Wherever possible, if some static information is known about dynamically loaded
classes (e.g., that the classes loaded all implement a known interface), then this can
greatly simplify the interaction with the classes and reduce the burden of operating
reflectively.
It is a common mistake to try to create a reflective framework that tries to account
for all possible circumstances, instead of dealing only with the cases that are imme‐
diately applicable to the problem domain.
How to Use Relection
The first step in any reflective operation is to get a Class object representing the
type to be operated on. From this, other objects, representing fields, methods, or
constructors can be accessed, and applied to instances of the unknown type.
To get an instance of an unknown type, the simplest way is to use the no-arg con‐
structor, which is made available directly via the Class object:
Class <?> clz = getSomeClassObject ();
Object rcvr = clz . newInstance ();
For constructors that take arguments, you will have to look up the precise construc‐
tor needed, represented as a Constructor object.
The Method objects are one of the most commonly used objects provided by Reflec‐
tion. We'll discuss them in detail—the Constructor and Field objects are similar in
many respects.
Method objects
A class object contains a Method object for each method on the class. These are
lazily created after classloading, and so aren't immediately visible in an IDE's
debugger.
Search WWH ::




Custom Search