THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

information about the class itself, such as the modifiers applied to it (public, abstract, final, and so
on) or the package it is contained in. Reflection is also sometimes called introspection; both terms use the
metaphor of asking the type to look at itself and tell you something. These capabilities can be used by type
browsers to show the structure of an application. They also form the first step for you to dynamically create
and manipulate objects.


Here's a simple example of a "type browser." Given the name of a class this program shows the class's
immediate superclass and lists all the public methods it declares:


import java.lang.reflect.*;
import static java.lang.System.out;
import static java.lang.System.err;


public class SimpleClassDesc {
public static void main(String[] args) {
Class type = null;
try {
type = Class.forName(args[0]);
} catch (ClassNotFoundException e) {
err.println(e);
return;
}


out.print("class " + type.getSimpleName());
Class superclass = type.getSuperclass();
if (superclass != null)
out.println(" extends " +
superclass.getCanonicalName());
else
out.println();


Method[] methods = type.getDeclaredMethods();
for (Method m : methods)
if (Modifier.isPublic(m.getModifiers()))
out.println(" " + m);
}
}


Given the fully qualified name of a class (such java.lang.String) the program first tries to obtain a
Class object for that class, using the static method Class.forName. If the class can't be found an
exception is thrown which the program catches and reports. Otherwise, the simple name of the classString,
for exampleis printed. Next the Class object is asked for its superclass's Class object. As long as the
named class is not Object and is a class rather than an interface, getSuperclass will return a
superclass's Class object. The name of the super class is printed in full using getCanonicalName (there
are a number of ways to name a class as you'll see in Section 16.1.4 on page 411). Next, the Class object is
asked for all the methods that it declares. The declared methods include all 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)

Free download pdf