http://java.sun.com/developer/technicalArticles/ALT/Reflection/
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
The ability to examine and manipulate a Java class from within itselfmay not sound like very much, but in other programming languages thisfeature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions definedwithin that program.
One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.
To see how reflection works, consider this simple example:
import java.lang.reflect.*; public class DumpMethods { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Method m[] = c.getDeclaredMethods(); for (int i = 0; i < m.length; i++) System.out.println(m[i].toString()); } catch (Throwable e) { System.err.println(e); } } } |
For an invocation of:
java DumpMethods java.util.Stack
the output is:
public java.lang.Object java.util.Stack.push( java.lang.Object) public synchronized java.lang.Object java.util.Stack.pop() public synchronized java.lang.Object java.util.Stack.peek() public boolean java.util.Stack.empty() public synchronized int java.util.Stack.search(java.lang.Object) |
That is, the method names of class java.util.Stack
are listed, along with their fully qualified parameter and return types.
This program loads the specified class using class.forName
, and then calls getDeclaredMethods
to retrieve the list of methods defined in the class. java.lang.reflect.Method
is a class representing a single class method.
The reflection classes, such as Method
, are found in java.lang.reflect. There are three steps that must be followed to use these classes. The first step is to obtain a java.lang.Class
object for the class that you want to manipulate. java.lang.Class
is used to represent classes and interfaces in a running Java program.
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 approachaccesses 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 presentself contained illustrations of how to tackle specific applicationsusing reflection.
instanceof
OperatorOnce Class information is in hand, often the next step is to ask basicquestions about the Class object. For example, the Class.isInstance
method can be used to simulate the instanceof
operator:
class A {} public class instance1 { public static void main(String args[]) { try { Class cls = Class.forName("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); } } } |
A
is created, and then classinstance objects are checked to see whether they are instances of
A
.
Integer(37)
is not, but
new A()
is.
One of the most valuable and basic uses of reflection is to find outwhat methods are defined within a class. To do this thefollowing code can be used:
import java.lang.reflect.*; 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("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); } } } |
getDeclaredMethods
to retrieve a list of
Method
objects, one for each method defined in the class. These include public, protected, package, and private methods. If you use
getMethods
in the program instead of
getDeclaredMethods
, you can also obtain information for inherited methods.
Once a list of the Method
objects has been obtained, it's simply a matter of displaying the information on parameter types, exceptiontypes, and the return type for each method. Each of these types,whether they are fundamental or class types, is in turn represented by aClass descriptor.
name = f1 decl class = class method1 param #0 class java.lang.Object param #1 int exc #0 class java.lang.NullPointerException return type = int ----- name = main decl class = class method1 param #0 class [Ljava.lang.String; return type = void ----- |
A similar approach is used to find out about the constructors of aclass. For example:
import java.lang.reflect.*; public class constructor1 { public constructor1() { } protected constructor1(int i, double d) { } public static void main(String args[]) { try { Class cls = Class.forName("constructor1"); Constructor ctorlist[] = cls.getDeclaredConstructors(); for (int i = 0; i < ctorlist.length; i++) { Constructor ct = ctorlist[i]; System.out.println("name = " + ct.getName()); System.out.println("decl class = " + ct.getDeclaringClass()); Class pvec[] = ct.getParameterTypes(); for (int j = 0; j < pvec.length; j++) System.out.println("param #" + j + " " + pvec[j]); Class evec[] = ct.getExceptionTypes(); for (int j = 0; j < evec.length; j++) System.out.println( "exc #" + j + " " + evec[j]); System.out.println("-----"); } } catch (Throwable e) { System.err.println(e); } } } |
When this program is run, the output is:
name = constructor1 decl class = class constructor1 ----- name = constructor1 decl class = class constructor1 param #0 int param #1 double ----- |
It's also possible to find out which data fields are defined in a class.To do this, the following code can be used:
import java.lang.reflect.*; public class field1 { private double d; public static final int i = 37; String s = "testing"; public static void main(String args[]) { try { Class cls = Class.forName("field1"); Field fieldlist[] = cls.getDeclaredFields(); for (int i = 0; i < fieldlist.length; i++) { Field fld = fieldlist[i]; System.out.println("name = " + fld.getName()); System.out.println("decl class = " + fld.getDeclaringClass()); System.out.println("type = " + fld.getType()); int mod = fld.getModifiers(); System.out.println("modifiers = " + Modifier.toString(mod)); System.out.println("-----"); } } catch (Throwable e) { System.err.println(e); } } } |
Modifier
. This is a reflection class that represents themodifiers found on a field member, for example "
private int
". The modifiers themselves are represented by an integer, and
Modifier.toString
is used to return a string representation in the "official" declaration order (such as "
static
" before "
final
"). The output of the program is:
name = d decl class = class field1 type = double modifiers = private ----- name = i decl class = class field1 type = int modifiers = public static final ----- name = s decl class = class field1 type = class java.lang.String modifiers = ----- |
getDeclaredFields
), or to also getinformation about fields defined in superclasses (
getFields
).
So far the examples that have been presented all relate to obtainingclass information. But it's also possible to use reflection in otherways, for example to invoke a method of a specified name.
To see how this works, consider the following example:
import java.lang.reflect.*; public class method2 { public int add(int a, int b) { return a + b; } public static void main(String args[]) { try { Class cls = Class.forName("method2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE; partypes[1] = Integer.TYPE; Method meth = cls.getMethod( "add", partypes); method2 methobj = new method2(); Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = meth.invoke(methobj, arglist); Integer retval = (Integer)retobj; System.out.println(retval.intValue()); } catch (Throwable e) { System.err.println(e); } } } |
add
method, but doesn'tknow this until execution time. That is, the name of the method isspecified during execution (this might be done by a JavaBeansdevelopment environment, for example). The above program shows a way ofdoing this.
getMethod
is used to find a method in the class that has two integer parameter types and that has the appropriate name. Once this method has been found and captured into a Method
object, it is invoked upon an object instance of the appropriate type. To invoke a method, aparameter list must be constructed, with the fundamental integer values37 and 47 wrapped in Integer
objects. The return value (84) is also wrapped in an Integer
object.
There is no equivalent to method invocation for constructors, becauseinvoking a constructor is equivalent to creating a new object (to be themost precise, creating a new object involves both memory allocation andobject construction). So the nearest equivalent to the previous example is to say:
import java.lang.reflect.*; public class constructor2 { public constructor2() { } public constructor2(int a, int b) { System.out.println( "a = " + a + " b = " + b); } public static void main(String args[]) { try { Class cls = Class.forName("constructor2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE; partypes[1] = Integer.TYPE; Constructor ct = cls.getConstructor(partypes); Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = ct.newInstance(arglist); } catch (Throwable e) { System.err.println(e); } } } |
Another use of reflection is to change the values of data fields inobjects. The value of this is again derived from the dynamic nature ofreflection, where a field can be looked up by name in an executingprogram and then have its value changed. This is illustrated by the following example:
import java.lang.reflect.*; public class field2 { public double d; public static void main(String args[]) { try { Class cls = Class.forName("field2"); Field fld = cls.getField("d"); field2 f2obj = new field2(); System.out.println("d = " + f2obj.d); fld.setDouble(f2obj, 12.34); System.out.println("d = " + f2obj.d); } catch (Throwable e) { System.err.println(e); } } } |
One final use of reflection is in creating and manipulating arrays. Arrays in the Java language are a specialized type of class, and an array reference can be assigned to an Object
reference.
To see how arrays work, consider the following example:
import java.lang.reflect.*; public class array1 { public static void main(String args[]) { try { Class cls = Class.forName( "java.lang.String"); Object arr = Array.newInstance(cls, 10); Array.set(arr, 5, "this is a test"); String s = (String)Array.get(arr, 5); System.out.println(s); } catch (Throwable e) { System.err.println(e); } } } |
A more complex manipulation of arrays is illustrated by the followingcode:
import java.lang.reflect.*; public class array2 { public static void main(String args[]) { int dims[] = new int[]{5, 10, 15}; Object arr = Array.newInstance(Integer.TYPE, dims); Object arrobj = Array.get(arr, 3); Class cls = arrobj.getClass().getComponentType(); System.out.println(cls); arrobj = Array.get(arrobj, 5); Array.setInt(arrobj, 10, 37); int arrcast[][][] = (int[][][])arr; System.out.println(arrcast[3][5][10]); } } |
Array.setInt
.
Note that the type of array that is created is dynamic, and does nothave to be known at compile time.
Java reflection is useful because it supports dynamic retrieval ofinformation about classes and data structures by name, and allows fortheir manipulation within an executing Java program. This feature isextremely powerful and has no equivalent in other conventional languagessuch as C, C++, Fortran, or Pascal.
Glen McCluskey has focused on programming languages since 1988. He consults in the areas of Java and C++ performance, testing, and technical documentation.