Over the next few pages you'll see how to perform a much more detailed examination of a class's supertypes
and its members.
Reflection also allows you to write code that performs actions that you can more simply execute directly in
code if you know what you are doing. Given the name of a class (which may not have existed when the
program was written) you can obtain a Class object and use that Class object to create new instances of
that class. You can interact with those objects just as you would with an object created via new. You can, for
example, invoke a method using reflection, as you will soon see, but it is much harder to understand than a
direct method invocation. You should use reflection only when you have exhausted all other object-oriented
design mechanisms. For example, you should not use a Method object as a "method pointer," because
interfaces and abstract classes are better tools. There are times when reflection is necessaryusually when
you're interpreting or displaying some other codebut use more direct means whenever possible.
Figure 16-1 (see next page) shows the classes and interfaces that support introspection. At the top, Type
represents all types that can exist in a Java programit is a marker interface containing no methods. All
concrete types are represented by an instance of class Class. The other types pertain to generic types:
parameterized types, type variables, wildcards, and generic arrays. The Constructor, Method, and
Field classes represent constructors, methods and fields, respectively. These are all Member instances and
are also subclasses of AccessibleObject (which pertains to access control). The classes Class,
Constructor, and Method are all GenericDeclaration instances because they can be declared in a
generic way. Finally, the class Class, the AccessibleObject subclasses, and the Package class are all
instances of AnnotatedElement because they can have annotations applied to them.
Figure 16-1. The Introspection Hierarchy