Java Reference
In-Depth Information
methods actually declared in the class but none that are inherited. Since
we're only interested in public methods, we ask the Method object for the
method's modifiers and ask the Modifier class if those modifiers include
public. If so the method is printed, otherwise it is ignored. Here's the
output when given the name of the Attr class from page 76 :
class Attr extends java.lang.Object
public java.lang.String Attr.getName()
public java.lang.String Attr.toString()
public java.lang.Object Attr.getValue()
public java.lang.Object Attr.setValue(java.lang.Object)
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 do-
ing. 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 sup-
port 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 oth-
er 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
 
Search WWH ::




Custom Search