One way of obtaining a Class object is to say:
Class c = Class.forName("java.lang.String");
to get the Class object for String. Another approach is to use:
Class c = int.class;
or
Class c = Integer.TYPE;
to obtain Class information on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper (such as Integer) for the fundamental type.
The second step is to call a method such as getDeclaredMethods, to get a list of all the methods declared by the class.
Once this information is in hand, then the third step is to use the reflection API to manipulate the information. For example, the sequence:
Class c = Class.forName("java.lang.String");
Method m[] = c.getDeclaredMethods();
System.out.println(m[0].toString());
will display a textual representation of the first method declared in String.
In the examples below, the three steps are combined to present self contained illustrations of how to tackle specific applications using reflection.
Simulating the instanceof Operator
Once Class information is in hand, often the next step is to ask basic questions about the Class object. For example, the Class.isInstance method can be used to simulate the instanceof operator:
package org.duke.java.reflect;
public class Instance1 {
public static void main(String[] args) {
try {
Class cls = Class.forName("org.duke.java.reflect.A");
boolean b1 = cls.isInstance(new Integer(37));
System.out.println(b1);
boolean b2 = cls.isInstance(new A());
System.out.println(b2);
} catch (Throwable e) {
System.err.println(e);
}
}
}
class A {
}
In this example, a Class object for A is created, and then class instance objects are checked to see whether they are instances of A. Integer(37) is not, but new A() is.
Finding Out About Methods of a Class
One of the most valuable and basic uses of reflection is to find out what methods are defined within a class. To do this the following code can be used:
package org.duke.java.reflect;
import java.lang.reflect.Method;
public class Method1 {
private int f1(Object p, int x) throws NullPointerException {
if (p == null)
throw new NullPointerException();
return x;
}
public static void main(String args[]) {
try {
Class cls = Class.forName("org.duke.java.reflect.Method1");
Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
System.out.println("name = " + m.getName());
System.out.println("decl class = " + m.getDeclaringClass());
Class pvec[] = m.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
Class evec[] = m.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("return type = " + m.getReturnType());
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}
The program first gets the Class description for method1, and then calls getDeclaredMethods to retrieve a list of Method objects, one