Home > Articles > Programming > Java

This chapter is from the book

Reflection

The reflection library gives you a very rich and elaborate toolset to write programs that manipulate Java code dynamically. This feature is heavily used in JavaBeans, the component architecture for Java (see Volume II for more on JavaBeans). Using reflection, Java can support tools like the ones to which users of Visual Basic have grown accustomed. In particular, when new classes are added at design or runtime, rapid application development tools can dynamically inquire about the capabilities of the classes that were added.

A program that can analyze the capabilities of classes is called reflective. The reflection mechanism is extremely powerful. As the next sections show, you can use it to

  • Analyze the capabilities of classes at runtime;
  • Inspect objects at runtime, for example, to write a single toString method that works for all classes;
  • Implement generic array manipulation code; and
  • Take advantage of Method objects that work just like function pointers in languages such as C++.

Reflection is a powerful and complex mechanism; however, it is of interest mainly to tool builders, not application programmers. If you are interested in programming applications rather than tools for other Java programmers, you can safely skip the remainder of this chapter and return to it later.

The Class Class

While your program is running, the Java runtime system always maintains what is called runtime type identification on all objects. This information keeps track of the class to which each object belongs. Runtime type information is used by the virtual machine to select the correct methods to execute.

However, you can also access this information by working with a special Java class. The class that holds this information is called, somewhat confusingly, Class. The getClass() method in the Object class returns an instance of Class type.

Employee e;
. . .
Class cl = e.getClass();

Just like an Employee object describes the properties of a particular employee, a Class object describes the properties of a particular class. Probably the most commonly used method of Class is getName. This returns the name of the class. For example, the statement

System.out.println(e.getClass().getName() + " " + e.getName());

prints

Employee Harry Hacker

if e is an employee, or

Manager Harry Hacker

if e is a manager.

If the class is in a package, the package name is part of the class name:

Date d = new Date();
Class cl = d.getClass();
String name = cl.getName(); // name is set to "java.util.Date"

You can obtain a Class object corresponding to a class name by using the static forName method.

String className = "java.util.Date";
Class cl = Class.forName(className);

You would use this method if the class name is stored in a string that varies at runtimeruntime. This works if className is the name of a class or interface. Otherwise, the forName method throws a checked exception. See the section "A Primer on Catching Exceptions" on page 219 to see how to supply an exception handler whenever you use this method.

A third method for obtaining an object of type Class is a convenient shorthand. If T is any Java type, then T.class is the matching class object. For example:

Class cl1 = Date.class; // if you import java.util.*;
Class cl2 = int.class;
Class cl3 = Double[].class;

Note that a Class object really describes a type, which may or may not be a class. For example, int is not a class, but int.class is nevertheless an object of type Class.

The virtual machine manages a unique Class object for each type. Therefore, you can use the == operator to compare class objects. For example:

if (e.getClass() == Employee.class) . . .

Another example of a useful method is one that lets you create an instance of a class on the fly. This method is called, naturally enough, newInstance(). For example,

e.getClass().newInstance();

creates a new instance of the same class type as e. The newInstance method calls the default constructor (the one that takes no parameters) to initialize the newly created object. An exception is thrown if the class has no default constructor.

Using a combination of forName and newInstance lets you create an object from a class name stored in a string.

String s = "java.util.Date";
Object m = Class.forName(s).newInstance();

A Primer on Catching Exceptions

We cover exception handling fully in Chapter 11, but in the meantime you will occasionally encounter methods that threaten to throw exceptions.

When an error occurs at runtime, a program can "throw an exception." Throwing an exception is more flexible than terminating the program because you can provide a handler that "catches" the exception and deals with it.

If you don't provide a handler, the program still terminates and prints a message to the console, giving the type of the exception. You may already have seen exception reports when you accidentally used a null reference or overstepped the bounds of an array.

There are two kinds of exceptions: unchecked exceptions and checked exceptions. With checked exceptions, the compiler checks that you provide a handler. However, many common exceptions, such as accessing a null reference, are unchecked. The compiler does not check whether you provide a handler for these errors—after all, you should spend your mental energy on avoiding these mistakes rather than coding handlers for them.

But not all errors are avoidable. If an exception can occur despite your best efforts, then the compiler insists that you provide a handler. The Class.forName method is an example of a method that throws a checked exception. In Chapter 11, you will see several exception handling strategies. For now, we just show you the simplest handler implementation.

Place one or more statements that might throw checked exceptions inside a try block. Then provide the handler code in the catch clause.

try
{
   statements that might throw exceptions
}
catch(Exception e)
{
   handler action
}

Here is an example:

try
{
   String name = . . .; // get class name
   Class cl = Class.forName(name); // might throw exception
   . . . // do something with cl
}
catch(Exception e)
{
   e.printStackTrace();
}

If the class name doesn't exist, the remainder of the code in the try block is skipped and the program enters the catch clause. (Here, we print a stack trace by using the printStackTrace method of the Throwable class. Throwable is the superclass of the Exception class.) If none of the methods in the try block throws an exception, the handler code in the catch clause is skipped.

You only need to supply an exception handler for checked exceptions. It is easy to find out which methods throw checked exceptions—the compiler will complain whenever you call a method that threatens to throw a checked exception and you don't supply a handler.

Using Reflection to Analyze the Capabilities of Classes

Here is a brief overview of the most important parts of the reflection mechanism for letting you examine the structure of a class.

The three classes Field, Method, and Constructor in the java.lang.reflect package describe the fields, methods, and constructors of a class, respectively. All three classes have a method called getName that returns the name of the item. The Field class has a method getType that returns an object, again of type Class, that describes the field type. The Method and Constructor classes have methods to report the types of the parameters, and the Method class also reports the return type. All three of these classes also have a method called getModifiers that returns an integer, with various bits turned on and off, that describes the modifiers used, such as public and static. You can then use the static methods in the Modifier class in the java.lang.reflect package to analyze the integer that getModifiers returns. Use methods like isPublic, isPrivate, or isFinal in the Modifier class to tell whether a method or constructor was public, private, or final. All you have to do is have the appropriate method in the Modifier class work on the integer that getModifiers returns. You can also use the Modifier.toString method to print the modifiers.

The getFields, getMethods, and getConstructors methods of the Class class return arrays of the public fields, methods, and constructors that the class supports. This includes public members of superclasses. The getDeclaredFields, getDeclaredMethods, and getDeclaredConstructors methods of the Class class return arrays consisting of all fields, methods, and constructors that are declared in the class. This includes private and protected members, but not members of superclasses.

Listing 5-6 shows you how to print out all information about a class. The program prompts you for the name of a class and then writes out the signatures of all methods and constructors as well as the names of all data fields of a class. For example, if you enter

java.lang.Double

the program prints

public class java.lang.Double extends java.lang.Number
{
    public java.lang.Double(java.lang.String);
    public java.lang.Double(double);

    public int hashCode();
    public int compareTo(java.lang.Object);
    public int compareTo(java.lang.Double);
    public boolean equals(java.lang.Object);
    public java.lang.String toString();
    public static java.lang.String toString(double);
    public static java.lang.Double valueOf(java.lang.String);
    public static boolean isNaN(double);
    public boolean isNaN();
    public static boolean isInfinite(double);
    public boolean isInfinite();
    public byte byteValue();
    public short shortValue();
    public int intValue();
    public long longValue();
    public float floatValue();
    public double doubleValue();
    public static double parseDouble(java.lang.String);
    public static native long doubleToLongBits(double);
    public static native long doubleToRawLongBits(double);
    public static native double longBitsToDouble(long);

    public static final double POSITIVE_INFINITY;
    public static final double NEGATIVE_INFINITY;
    public static final double NaN;
    public static final double MAX_VALUE;
    public static final double MIN_VALUE;
    public static final java.lang.Class TYPE;
    private double value;
    private static final long serialVersionUID;
}

What is remarkable about this program is that it can analyze any class that the Java interpreter can load, not just the classes that were available when the program was compiled. We use this program in the next chapter to peek inside the inner classes that the Java compiler generates automatically.

Listing 5-6. ReflectionTest.java

  1. import java.util.*;
  2. import java.lang.reflect.*;
  3.
  4. /**
  5.  * This program uses reflection to print all features of a class.
  6.  * @version 1.1 2004-02-21
  7.  * @author Cay Horstmann
  8.  */
  9. public class ReflectionTest
 10. {
 11.    public static void main(String[] args)
 12.    {
 13.       // read class name from command line args or user input
 14.       String name;
 15.       if (args.length > 0) name = args[0];
 16.       else
 17.       {
 18.          Scanner in = new Scanner(System.in);
 19.          System.out.println("Enter class name (e.g. java.util.Date): ");
 20.          name = in.next();
 21.       }
 22.
 23.       try
 24.       {
 25.          // print class name and superclass name (if != Object)
 26.          Class cl = Class.forName(name);
 27.          Class supercl = cl.getSuperclass();
 28.          String modifiers = Modifier.toString(cl.getModifiers());
 29.          if (modifiers.length() > 0) System.out.print(modifiers + " ");
 30.          System.out.print("class " + name);
 31.          if (supercl != null && supercl != Object.class) System.out.print(" extends "
 32.                + supercl.getName());
 33.
 34.          System.out.print("\n{\n");
 35.          printConstructors(cl);
 36.          System.out.println();
 37.          printMethods(cl);
 38.          System.out.println();
 39.          printFields(cl);
 40.          System.out.println("}");
 41.       }
 42.       catch (ClassNotFoundException e)
 43.       {
 44.          e.printStackTrace();
 45.       }
 46.       System.exit(0);
 47.    }
 48.
 49.    /**
 50.     * Prints all constructors of a class
 51.     * @param cl a class
 52.     */
 53.    public static void printConstructors(Class cl)
 54.    {
 55.       Constructor[] constructors = cl.getDeclaredConstructors();
 56.
 57.       for (Constructor c : constructors)
 58.       {
 59.          String name = c.getName();
 60.          System.out.print("   ");
 61.          String modifiers = Modifier.toString(c.getModifiers());
 62.          if (modifiers.length() > 0) System.out.print(modifiers + " ");
 63.          System.out.print(name + "(");
 64.
 65.          // print parameter types
 66.          Class[] paramTypes = c.getParameterTypes();
 67.          for (int j = 0; j < paramTypes.length; j++)
 68.          {
 69.             if (j > 0) System.out.print(", ");
 70.             System.out.print(paramTypes[j].getName());
 71.          }
 72.          System.out.println(")");
 73.       }
 74.    }
 75.
 76.    /**
 77.     * Prints all methods of a class
 78.     * @param cl a class
 79.     */
 80.    public static void printMethods(Class cl)
 81.    {
 82.       Method[] methods = cl.getDeclaredMethods();
 83.
 84.       for (Method m : methods)
 85.       {
 86.          Class retType = m.getReturnType();
 87.          String name = m.getName();
 88.
 89.          System.out.print("   ");
 90.          // print modifiers, return type, and method name
 91.          String modifiers = Modifier.toString(m.getModifiers());
 92.          if (modifiers.length() > 0) System.out.print(modifiers + " ");
 93.          System.out.print(retType.getName() + " " + name + "(");
 94.
 95.          // print parameter types
 96.          Class[] paramTypes = m.getParameterTypes();
 97.          for (int j = 0; j < paramTypes.length; j++)
 98.          {
 99.             if (j > 0) System.out.print(", ");
100.             System.out.print(paramTypes[j].getName());
101.          }
102.          System.out.println(")");
103.       }
104.    }
105.
106.    /**
107.     * Prints all fields of a class
108.     * @param cl a class
109.     */
110.    public static void printFields(Class cl)
111.    {
112.       Field[] fields = cl.getDeclaredFields();
113.
114.       for (Field f : fields)
115.       {
116.          Class type = f.getType();
117.          String name = f.getName();
118.          System.out.print("   ");
119.          String modifiers = Modifier.toString(f.getModifiers());
120.          if (modifiers.length() > 0) System.out.print(modifiers + " ");
121.          System.out.println(type.getName() + " " + name + "");
122.       }
123.    }
124. }

Using Reflection to Analyze Objects at Runtime

In the preceding section, we saw how we can find out the names and types of the data fields of any object:

  • Get the corresponding Class object.
  • Call getDeclaredFields on the Class object.

In this section, we go one step further and actually look at the contents of the data fields. Of course, it is easy to look at the contents of a specific field of an object whose name and type are known when you write a program. But reflection lets you look at fields of objects that were not known at compile time.

The key method to achieve this examination is the get method in the Field class. If f is an object of type Field (for example, one obtained from getDeclaredFields) and obj is an object of the class of which f is a field, then f.get(obj) returns an object whose value is the current value of the field of obj. This is all a bit abstract, so let's run through an example.

Employee harry = new Employee("Harry Hacker", 35000, 10, 1, 1989);
Class cl = harry.getClass();
   // the class object representing Employee
Field f = cl.getDeclaredField("name");
   // the name field of the Employee class
Object v = f.get(harry);
   // the value of the name field of the harry object
   // i.e., the String object "Harry Hacker"

Actually, there is a problem with this code. Because the name field is a private field, the get method will throw an IllegalAccessException. You can only use the get method to get the values of accessible fields. The security mechanism of Java lets you find out what fields any object has, but it won't let you read the values of those fields unless you have access permission.

The default behavior of the reflection mechanism is to respect Java access control. However, if a Java program is not controlled by a security manager that disallows it, you can override access control. To do this, invoke the setAccessible method on a Field, Method, or Constructor object. For example:

f.setAccessible(true); // now OK to call f.get(harry);

The setAccessible method is a method of the AccessibleObject class, the common superclass of the Field, Method, and Constructor classes. This feature is provided for debuggers, persistent storage, and similar mechanisms. We use it for a generic toString method later in this section.

There is another issue with the get method that we need to deal with. The name field is a String, and so it is not a problem to return the value as an Object. But suppose we want to look at the salary field. That is a double, and in Java, number types are not objects. To handle this, you can either use the getDouble method of the Field class, or you can call get, whereby the reflection mechanism automatically wraps the field value into the appropriate wrapper class, in this case, Double.

Of course, you can also set the values that you can get. The call f.set(obj, value) sets the field represented by f of the object obj to the new value.

Listing 5-7 shows how to write a generic toString method that works for any class. It uses getDeclaredFields to obtain all data fields. It then uses the setAccessible convenience method to make all fields accessible. For each field, it obtains the name and the value. Listing 5-7 turns each value into a string by recursively invoking toString.

class ObjectAnalyzer
{
  public String toString(Object obj)
  {
      Class cl = obj.getClass();
      . . .
      String r = cl.getName();
      // inspect the fields of this class and all superclasses
      do
      {
         r += "[";
         Field[] fields = cl.getDeclaredFields();
         AccessibleObject.setAccessible(fields, true);
         // get the names and values of all fields
         for (Field f : fields)
         {
            if (!Modifier.isStatic(f.getModifiers()))
            {
              if (!r.endsWith("[")) r += ","
              r += f.getName() + "=";
              try
              {
                 Object val = f.get(obj);
                 r += toString(val);
              }
              catch (Exception e) { e.printStackTrace(); }
            }
         }
         r += "]";
         cl = cl.getSuperclass();
      }
      while (cl != null);
      return r;
  }
  . . .
}

The complete code in Listing 5-7 needs to address a couple of complexities. Cycles of references could cause an infinite recursion. Therefore, the ObjectAnalyzer keeps track of objects that were already visited. Also, to peek inside arrays, you need a different approach. You'll learn about the details in the next section.

You can use this toString method to peek inside any object. For example, the call

ArrayList<Integer> squares = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) squares.add(i * i);
System.out.println(new ObjectAnalyzer().toString(squares));

yields the printout

java.util.ArrayList[elementData=class java.lang.Object[]{java.lang.Integer[value=1][][],
java.lang.Integer[value=4][][],java.lang.Integer[value=9][][],java.lang.Integer[value=16][][],
java.lang.Integer[value=25][][],null,null,null,null,null},size=5][modCount=5][][]

You can use this generic toString method to implement the toString methods of your own classes, like this:

public String toString()
{
   return new ObjectAnalyzer().toString(this);
}

This is a hassle-free method for supplying a toString method that you may find useful in your own programs.

Listing 5-7. ObjectAnalyzerTest.java

 1. import java.lang.reflect.*;
 2. import java.util.*;
 3.
 4. /**
 5.  * This program uses reflection to spy on objects.
 6.  * @version 1.11 2004-02-21
 7.  * @author Cay Horstmann
 8.  */
 9. public class ObjectAnalyzerTest
10. {
11.    public static void main(String[] args)
12.    {
13.       ArrayList<Integer> squares = new ArrayList<Integer>();
14.       for (int i = 1; i <= 5; i++)
15.          squares.add(i * i);
16.       System.out.println(new ObjectAnalyzer().toString(squares));
17.    }
18. }
19.
20. class ObjectAnalyzer
21. {
22.   /**
23.    * Converts an object to a string representation that lists all fields.
24.    * @param obj an object
25.    * @return a string with the object's class name and all field names and
26.    * values
27.    */
28.   public String toString(Object obj)
29.   {
30.      if (obj == null) return "null";
31.      if (visited.contains(obj)) return "...";
32.      visited.add(obj);
33.      Class cl = obj.getClass();
34.      if (cl == String.class) return (String) obj;
35.      if (cl.isArray())
36.      {
37.         String r = cl.getComponentType() + "[]{";
38.         for (int i = 0; i < Array.getLength(obj); i++)
39.         {
40.            if (i > 0) r += ",";
41.            Object val = Array.get(obj, i);
42.            if (cl.getComponentType().isPrimitive()) r += val;
43.            else r += toString(val);
44.         }
45.         return r + "}";
46.      }
47.
48.      String r = cl.getName();
49.      // inspect the fields of this class and all superclasses
50.      do
51.      {
52.         r += "[";
53.         Field[] fields = cl.getDeclaredFields();
54.         AccessibleObject.setAccessible(fields, true);
55.         // get the names and values of all fields
56.         for (Field f : fields)
57.         {
58.            if (!Modifier.isStatic(f.getModifiers()))
59.            {
60.               if (!r.endsWith("[")) r += ",";
61.               r += f.getName() + "=";
62.               try
63.               {
64.                  Class t = f.getType();
65.                  Object val = f.get(obj);
66.                  if (t.isPrimitive()) r += val;
67.                  else r += toString(val);
68.               }
69.               catch (Exception e)
70.               {
71.                  e.printStackTrace();
72.               }
73.            }
74.         }
75.         r += "]";
76.         cl = cl.getSuperclass();
77.      }
78.      while (cl != null);
79.
80.      return r;
81.   }
82.
83.   private ArrayList<Object> visited = new ArrayList<Object>();
84. }

Using Reflection to Write Generic Array Code

The Array class in the java.lang.reflect package allows you to create arrays dynamically. For example, when you use this feature with the arraycopy method from Chapter 3, you can dynamically expand an existing array while preserving the current contents.

The problem we want to solve is pretty typical. Suppose you have an array of some type that is full and you want to grow it. And suppose you are sick of writing the grow-and-copy code by hand. You want to write a generic method to grow an array.

Employee[] a = new Employee[100];
. . .
// array is full
a = (Employee[]) arrayGrow(a);

How can we write such a generic method? It helps that an Employee[] array can be converted to an Object[] array. That sounds promising. Here is a first attempt to write a generic method. We simply grow the array by 10% + 10 elements (because the 10 percent growth is not substantial enough for small arrays).

static Object[] badArrayGrow(Object[] a) // not useful
{
   int newLength = a.length * 11 / 10 + 10;
   Object[] newArray = new Object[newLength];
   System.arraycopy(a, 0, newArray, 0, a.length);
   return newArray;
}

However, there is a problem with actually using the resulting array. The type of array that this code returns is an array of objects (Object[]) because we created the array using the line of code

new Object[newLength]

An array of objects cannot be cast to an array of employees (Employee[]). Java would generate a ClassCastException at runtime. The point is, as we mentioned earlier, that a Java array remembers the type of its entries, that is, the element type used in the new expression that created it. It is legal to cast an Employee[] temporarily to an Object[] array and then cast it back, but an array that started its life as an Object[] array can never be cast into an Employee[] array. To write this kind of generic array code, we need to be able to make a new array of the same type as the original array. For this, we need the methods of the Array class in the java.lang.reflect package. The key is the static newInstance method of the Array class that constructs a new array. You must supply the type for the entries and the desired length as parameters to this method.

Object newArray = Array.newInstance(componentType, newLength);

To actually carry this out, we need to get the length and component type of the new array.

We obtain the length by calling Array.getLength(a). The static getLength method of the Array class returns the length of any array. To get the component type of the new array:

  1. First, get the class object of a.
  2. Confirm that it is indeed an array.
  3. Use the getComponentType method of the Class class (which is defined only for class objects that represent arrays) to find the right type for the array.

Why is getLength a method of Array but getComponentType a method of Class? We don't know—the distribution of the reflection methods seems a bit ad hoc at times.

Here's the code:

static Object goodArrayGrow(Object a) // useful
{
   Class cl = a.getClass();
   if (!cl.isArray()) return null;
   Class componentType = cl.getComponentType();
   int length = Array.getLength(a);
   int newLength = length * 11 / 10 + 10;
   Object newArray = Array.newInstance(componentType, newLength);
   System.arraycopy(a, 0, newArray, 0, length);
   return newArray;
}

Note that this arrayGrow method can be used to grow arrays of any type, not just arrays of objects.

int[] a = { 1, 2, 3, 4 };
a = (int[]) goodArrayGrow(a);

To make this possible, the parameter of goodArrayGrow is declared to be of type Object, not an array of objects (Object[]). The integer array type int[] can be converted to an Object, but not to an array of objects!

Listing 5-8 shows both array grow methods in action. Note that the cast of the return value of badArrayGrow will throw an exception.

Listing 5-8. ArrayGrowTest.java

 1. import java.lang.reflect.*;
 2.
 3. /**
 4.  * This program demonstrates the use of reflection for manipulating arrays.
 5.  * @version 1.01 2004-02-21
 6.  * @author Cay Horstmann
 7.  */
 8. public class ArrayGrowTest
 9. {
10.    public static void main(String[] args)
11.    {
12.       int[] a = { 1, 2, 3 };
13.       a = (int[]) goodArrayGrow(a);
14.       arrayPrint(a);
15.
16.       String[] b = { "Tom", "Dick", "Harry"};
17.       b = (String[]) goodArrayGrow(b);
18.       arrayPrint(b);
19.
20.       System.out.println("The following call will generate an exception.");
21.       b = (String[]) badArrayGrow(b);
22.    }
23.
24.    /**
25.     * This method attempts to grow an array by allocating a new array and copying all elements.
26.     * @param a the array to grow
27.     * @return a larger array that contains all elements of a. However, the returned array has
28.     * type Object[], not the same type as a
29.     */
30.    static Object[] badArrayGrow(Object[] a)
31.    {
32.       int newLength = a.length * 11 / 10 + 10;
33.       Object[] newArray = new Object[newLength];
34.       System.arraycopy(a, 0, newArray, 0, a.length);
35.       return newArray;
36.    }
37.
38.    /**
39.     * This method grows an array by allocating a new array of the same type and
40.     * copying all elements.
41.     * @param a the array to grow. This can be an object array or a primitive
42.     * type array
43.     * @return a larger array that contains all elements of a.
44.     */
45.    static Object goodArrayGrow(Object a)
46.    {
47.       Class cl = a.getClass();
48.       if (!cl.isArray()) return null;
49.       Class componentType = cl.getComponentType();
50.       int length = Array.getLength(a);
51.       int newLength = length * 11 / 10 + 10;
52.
53.       Object newArray = Array.newInstance(componentType, newLength);
54.       System.arraycopy(a, 0, newArray, 0, length);
55.       return newArray;
56.    }
57.
58.    /**
59.     * A convenience method to print all elements in an array
60.     * @param a the array to print. It can be an object array or a primitive type array
61.     */
62.    static void arrayPrint(Object a)
63.    {
64.       Class cl = a.getClass();
65.       if (!cl.isArray()) return;
66.       Class componentType = cl.getComponentType();
67.       int length = Array.getLength(a);
68.       System.out.print(componentType.getName() + "[" + length + "] = { ");
69.       for (int i = 0; i < Array.getLength(a); i++)
70.          System.out.print(Array.get(a, i) + " ");
71.       System.out.println("}");
72.    }
73. }

Method Pointers!

On the surface, Java does not have method pointers—ways of giving the location of a method to another method so that the second method can invoke it later. In fact, the designers of Java have said that method pointers are dangerous and error prone and that Java interfaces (discussed in the next chapter) are a superior solution. However, as of Java 1.1, it turns out that Java does have method pointers, as a (perhaps accidental) by-product of the reflection package.

To see method pointers at work, recall that you can inspect a field of an object with the get method of the Field class. Similarly, the Method class has an invoke method that lets you call the method that is wrapped in the current Method object. The signature for the invoke method is

Object invoke(Object obj, Object... args)

The first parameter is the implicit parameter, and the remaining objects provide the explicit parameters. (Before Java SE 5.0, you had to pass an array of objects or null if the method had no explicit parameters.)

For a static method, the first parameter is ignored—you can set it to null.

For example, if m1 represents the getName method of the Employee class, the following code shows how you can call it:

String n = (String) m1.invoke(harry);

As with the get and set methods of the Field type, there's a problem if the parameter or return type is not a class but a primitive type. You either rely on autoboxing or, before Java SE 5.0, wrap primitive types into their corresponding wrappers.

Conversely, if the return type is a primitive type, the invoke method will return the wrapper type instead. For example, suppose that m2 represents the getSalary method of the Employee class. Then, the returned object is actually a Double, and you must cast it accordingly. As of Java SE 5.0, automatic unboxing takes care of the rest.

double s = (Double) m2.invoke(harry);

How do you obtain a Method object? You can, of course, call getDeclaredMethods and search through the returned array of Method objects until you find the method that you want. Or, you can call the getMethod method of the Class class. This is similar to the getField method that takes a string with the field name and returns a Field object. However, there may be several methods with the same name, so you need to be careful that you get the right one. For that reason, you must also supply the parameter types of the desired method. The signature of getMethod is

Method getMethod(String name, Class... parameterTypes)

For example, here is how you can get method pointers to the getName and raiseSalary methods of the Employee class:

Method m1 = Employee.class.getMethod("getName");
Method m2 = Employee.class.getMethod("raiseSalary", double.class);

(Before Java SE 5.0, you had to package the Class objects into an array or to supply null if there were no parameters.)

Now that you have seen the rules for using Method objects, let's put them to work. Listing 5-9 is a program that prints a table of values for a mathematical function such as Math.sqrt or Math.sin. The printout looks like this:

public static native double java.lang.Math.sqrt(double)
       1.0000 |      1.0000
       2.0000 |      1.4142
       3.0000 |      1.7321
       4.0000 |      2.0000
       5.0000 |      2.2361
       6.0000 |      2.4495
       7.0000 |      2.6458
       8.0000 |      2.8284
       9.0000 |      3.0000
      10.0000 |      3.1623

The code for printing a table is, of course, independent of the actual function that is being tabulated.

double dx = (to - from) / (n - 1);
for (double x = from; x <= to; x += dx)
{
   double y = (Double) f.invoke(null, x);
   System.out.printf("%10.4f | %10.4f%n", x, y);
}

Here, f is an object of type Method. The first parameter of invoke is null because we are calling a static method.

To tabulate the Math.sqrt function, we set f to

Math.class.getMethod("sqrt", double.class)

That is the method of the Math class that has the name sqrt and a single parameter of type double.

Listing 5-9 shows the complete code of the generic tabulator and a couple of test runs.

Listing 5-9. MethodPointerTest.java

 1. import java.lang.reflect.*;
 2.
 3. /**
 4.  * This program shows how to invoke methods through reflection.
 5.  * @version 1.1 2004-02-21
 6.  * @author Cay Horstmann
 7.  */
 8. public class MethodPointerTest
 9. {
10.   public static void main(String[] args) throws Exception
11.   {
12.      // get method pointers to the square and sqrt methods
13.      Method square = MethodPointerTest.class.getMethod("square", double.class);
14.      Method sqrt = Math.class.getMethod("sqrt", double.class);
15.
16.      // print tables of x- and y-values
17.
18.      printTable(1, 10, 10, square);
19.      printTable(1, 10, 10, sqrt);
20.   }
21.
22.   /**
23.    * Returns the square of a number
24.    * @param x a number
25.    * @return x squared
26.    */
27.   public static double square(double x)
28.   {
29.      return x * x;
30.   }
31.
32.   /**
33.    * Prints a table with x- and y-values for a method
34.    * @param from the lower bound for the x-values
35.    * @param to the upper bound for the x-values
36.    * @param n the number of rows in the table
37.    * @param f a method with a double parameter and double return value
38.    */
39.   public static void printTable(double from, double to, int n, Method f)
40.   {
41.      // print out the method as table header
42.      System.out.println(f);
43.
44.      double dx = (to - from) / (n - 1);
45.
46.      for (double x = from; x <= to; x += dx)
47.      {
48.         try
49.         {
50.            double y = (Double) f.invoke(null, x);
51.            System.out.printf("%10.4f | %10.4f%n", x, y);
52.         }
53.         catch (Exception e)
54.         {
55.            e.printStackTrace();
56.         }
57.      }
58.   }
59. }

As this example shows clearly, you can do anything with Method objects that you can do with function pointers in C (or delegates in C#). Just as in C, this style of programming is usually quite inconvenient and always error prone. What happens if you invoke a method with the wrong parameters? The invoke method throws an exception.

Also, the parameters and return values of invoke are necessarily of type Object. That means you must cast back and forth a lot. As a result, the compiler is deprived of the chance to check your code. Therefore, errors surface only during testing, when they are more tedious to find and fix. Moreover, code that uses reflection to get at method pointers is significantly slower than code that simply calls methods directly.

For that reason, we suggest that you use Method objects in your own programs only when absolutely necessary. Using interfaces and inner classes (the subject of the next chapter) is almost always a better idea. In particular, we echo the developers of Java and suggest not using Method objects for callback functions. Using interfaces for the callbacks (see the next chapter as well) leads to code that runs faster and is a lot more maintainable.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020