Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Java Reflection


Dr. Dobb's Journal January 1998: Java Reflection

Not just for tool developers

Chris is president of Softeq Development, a software-development consulting company. Chris can be contacted at [email protected].


Sidebar: Reflecting on Beans

The JDK 1.1 Reflection API provides Java code with a means of introspection. Using Reflection, you can not only discover the fields, methods, and constructors of loaded classes, but you can dynamically manipulate them within the basic security framework as well.

Most discussions about Reflection focus on the fact that the Core Reflection API is used for Beans, object inspectors, debuggers, class browsers, and such run-time services as Object Serialization (see the accompanying text box entitled "Reflecting on Beans"). Although true, this emphasis tends to mislead developers of "workaday" applications into thinking that they can ignore Reflection, when it can actually make such applications more powerful, as I'll demonstrate in this article.

The switch Statement

Among the applications I develop are servers that accept and process transactions delivered by clients via a TCP/IP socket connection. These transactions typically consist of a command, followed by zero or more arguments. Prior to JDK 1.1, I often used a switch statement with a case for each command.

The switch statement, however, tends to make things difficult. As the possible number of commands to be processed becomes large, the volume of code in the method that processes the commands tends to become unmanageable; this turns those who have to support your code into enemies. You are also likely to be stung by the omission of a break statement -- and I know of few programmers who haven't been guilty of this at least once in their career. As convenient as it would be to use a statement such as case "abc": to process command "abc," you are faced with the restriction that limits the value of the case label to byte, char, short, int, or long. It should come as no surprise that I welcomed an alternative to the switch statement.

My solution, made possible with Reflection in JDK 1.1, involves the following:

  • 1. For each command to be processed, you provide a method whose name is identical to the command or which can be derived from the command.
  • 2. Obtain a Method object that reflects the method associated with the command being processed.
  • 3. Dynamically invoke the underlying method represented by this Method object, passing the appropriate arguments.

To illustrate, I wrote ReflectionDemo.java (see Listing One) which reads commands (see Table 1) from standard input, processes each command, and displays the result on standard output. The code was developed using JDK 1.1.1 Version 3 running on Linux (Slackware 96), and portability was verified on Windows NT Workstation 4.0 and AIX 4.2.

Dynamic Invocation: The Key to it All

Since my approach centers around dynamic invocation of methods, you need to know how this is done. First, you determine the class of the object containing the method you wish to invoke. To do this, use the getClass() method. This returns an object of type Class that represents the run-time class of the object on which it is invoked. Once you know the class, you must discover whether or not that class contains the method you want to invoke. As you know, a class can contain any number of methods with identical names; what makes them unique is the number and type of arguments they expect to receive. The getMethod() method, which is used to discover whether a class contains a method, takes two arguments:

  • A String that contains the name of the method in question.
  • An array of Class objects that identify that method's formal parameter types in the order in which they are declared.

When you invoke getMethod(), the method returns a Method object, which reflects the public method that exactly fits the description specified by the two arguments. If no such public method exists, a NoSuchMethodException is thrown. Now that you have an object reflecting the underlying method, you use the invoke() method to dynamically invoke it. The arguments you pass to the method are the object returned by getClass() and an array of Objects containing the actual arguments.

Listing Two presents class Invoker, which contains a single class method, dynaCall(), which performs the steps just described. The dynaCall() method receives three arguments:

  • The object containing the method you wish to invoke.
  • The name of the method.
  • An instance of class ArgumentHolder.

Taming Unruly Arguments with a Helper Class

ArgumentHolder (see Listing Three) is a helper class that simplifies the task of passing a large or variable number of arguments. If you have used the AWT, you encountered a helper class whenever you used GridBagConstraints to specify constraints for components laid out using the GridBagLayout class. As its name implies, ArgumentHolder holds an array of arguments. You add an argument to the array using one of the forms of the setArgument() method. As the method adds an argument to the args array, it stores a Class object describing the type of the argument in the corresponding element of the array cl. Upon examining the code, you are probably wondering why there are so many varieties of the setArgument() method. The first 16 are implemented to handle the eight primitive Java types (boolean, byte, char, short, int, long, float, and double). A public static final instance variable named TYPE in each of the classes Boolean, Byte, Character, Short, Integer, Long, Float, and Double contains a Class object representing the primitive type for which the class provides a wrapper. Since these variables are the only way by which the class of primitives can be referenced (you can't invoke the getClass() method on a primitive), the 16 special setArgument() methods are necessary.

Using What You Just Learned

InvokerTest.java (Listing Four) demonstrates how ArgumentHolder and Invoker are used. By running the program, you can see that the setArgument() method of ArgumentHolder can handle a primitive (int) and a wrapped primitive (Integer). You can also see that the dynaCall() method of Invoker can handle a method that receives an array, and one that receives multiple arguments of differing types. You may wish to experiment and add some dynamically invoked methods of your own to the code.

The ReflectionDemo.java program consists of a loop in which I read input from the console until "quit" is entered. For each line of input read, I invoke the processCommand() method, which invokes extractCommand() and extractArguments() to decompose the command line. The extractArguments() method makes the assumption that if the parseInteger() class method of class Integer throws a NumberFormatException, the token passed to the method should be treated as a String. This assumption is valid since, for simplicity, I have limited the data with which I am working to simple numbers and strings. If you were writing a more sophisticated application, you would provide more sophisticated code. Concatenating the string "meth" and the string returned by extractCommand() gives the name of the method that processes the command (note that extractCommand() forces the first character of the command to uppercase). You can see that the code contains methods whose names are methAdd(), methConcat(), methHelp(), methMinmax(), methQuit(), and methRand(). Method extractArguments() returns an instance of ArgumentHolder. I pass the class of the object containing the method I wish to invoke, the name of the method, and the ArgumentHolder to the class method dynaCall() of class Invoker. The result is returned as a String, which I display. The switch statement that I had set about to eliminate is absent.

Additional Benefits

In addition to avoiding use of the switch statement, you will find that the approach I just described does not require a large amount of code. It also offers the advantage of facilitating the addition of commands. If, for example, you wanted to add a command, subtract, which would subtract one number from another, you would simply add "subtract" to the list of commands displayed by methHelp() and add Example 1 to the ReflectionDemo class.

Conclusion

The Core Reflection is a powerful tool. Like any powerful tool, however, it does require time and practice to understand and master. As you have seen from the example I presented, Reflection is not just for tools developers. It does, indeed, have a place in the toolkit of the applications programmer.

DDJ

Listing One

import java.io.BufferedReader;import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.Math;
import java.util.Random;
import java.util.StringTokenizer;
public class ReflectionDemo {


</p>
  Random rand;
  BufferedReader consoleIn;
  ReflectionDemo() {
    consoleIn = new BufferedReader(new InputStreamReader(System.in));
    rand = new Random();
  }
  String getCommandLine() throws IOException {
    System.out.print(">");
    System.out.flush();
    String commandLine = consoleIn.readLine();
    if (commandLine == null)
      return "Q";
    if (commandLine.length() == 0)
      return "Q";
    else
      return commandLine;
  }
  String extractCommand(String commandLine) {
    StringTokenizer t = new StringTokenizer(commandLine);
    String cmd = t.nextToken().toLowerCase();
    return cmd.substring(0,1).toUpperCase() + cmd.substring(1);
  }
  ArgumentHolder extractArguments(String cmd) {
    StringTokenizer t = new StringTokenizer(cmd);
    int tokenCount = t.countTokens();
    ArgumentHolder a = new ArgumentHolder();
    String token = t.nextToken();
    while(t.hasMoreTokens()) {
      token = t.nextToken();
      try {
        int i = Integer.parseInt(token);
        a.setArgument(i);
      }
      catch (NumberFormatException e) {
        a.setArgument(token);
      }
    }
    return a;
  }
  public String methAdd(int i1, int i2) {
    return Integer.toString(i1) + " + " + 
      Integer.toString(i2) + " = " + Integer.toString(i1 + i2);
  }
  public String methConcat(String s1, String s2) {
    return "the concatenated string is " + s1 + s2;
  }
  public String methH() {
    return methHelp();
  }
  public String methHelp() {
    final String[] helpMessages = 
      {"ReflectionDemo Version 1.0",
       "valid commands are:",
       "add int1 int2",
       "concat string1 string 2",
       "help",
       "minmax int1 int2 int3",
       "quit",
       "rand"
      };
    for (int i = 0; i < helpMessages.length; ++i)
      System.out.println(helpMessages[i]);
    return "";
  }
  public String methMinmax(int i1, int i2, int i3) {
    return ("min = " + 
      Integer.toString(java.lang.Math.min(java.lang.Math.min(
        i1,i2),i3)) + ", max = " + Integer.toString(
        java.lang.Math.max(java.lang.Math.max(i1,i2),i3)));
  }
  public String methQ() {
    return methQuit();
  }
  public String methQuit() {
    return "quitting";
  }
  public String methRand() {
    return "the random number is " + Integer.toString(rand.nextInt());
  }
  String processCommand(String cmd) {
    try {
      String meth = "meth" + extractCommand(cmd);
      ArgumentHolder a = extractArguments(cmd);
      return (String)(Invoker.dynaCall(this, meth,a));
    }
    catch (NoSuchMethodException e) {
      return "no method to process command " + cmd;
    }
    catch (InvocationTargetException e) {
      System.out.println("trace:");
      e.printStackTrace();
      return "InvocationTargetException processing command" + cmd;
    }
    catch (IllegalAccessException e) {
      System.out.println("trace:");
      e.printStackTrace();
      return "IllegalAccessException processing command" + cmd;
    } 
  }
  public static void main(String args[]) {
    boolean allOK = true;
    String line;


</p>
    ReflectionDemo myClient = new ReflectionDemo();


</p>
    System.out.println("Reflection Demo Version 1.0");
    System.out.println("Enter command at the prompt");
    System.out.println("Type h (or H) for help");
    while(allOK) {
      try {
        line = myClient.getCommandLine();
        if (line == null)
          allOK = false;
        else {
          System.out.println(myClient.processCommand(line));
          if (line.substring(0,1).toUpperCase().equals("Q")) 
            allOK = false;
        }
      }
      catch (IOException e) {
        e.printStackTrace();
        allOK = false;
      }
    }
    System.exit(0);
  }
}

Back to Article

Listing Two

import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;


</p>
public class Invoker {
  static Object dynaCall(Object c, String m, ArgumentHolder a) 
    throws NoSuchMethodException, InvocationTargetException, 
      IllegalAccessException {
    Method meth = c.getClass().getMethod(m, a.getArgumentClasses()); 
    return (meth.invoke(c, a.getArguments()));
  }
}

Back to Article

Listing Three

public class ArgumentHolder {  protected Class[] cl;
  protected Object[] args;
  protected int argc;


</p>
  ArgumentHolder() {
    argc = 0;
    cl = new Class[0];
    args = new Object[0];
  }
  ArgumentHolder(int argc) {
    this.argc = argc;
    cl = new Class[argc];
    args = new Object[argc];
  }
  public Class[] getArgumentClasses() {
    return cl;
  }
  public Object[] getArguments() {
    return args;
  }
  public int setArgument(boolean b) {
    return this.setArgument(argc, new Boolean(b), Boolean.TYPE);
  }
  public int setArgument(int argnum, boolean b) {
    return this.setArgument(argnum, new Boolean(b), Boolean.TYPE);
  }
  public int setArgument(byte b) {
    return this.setArgument(argc, new Byte(b), Byte.TYPE);
  }


</p>
  public int setArgument(int argnum, byte b) {
    return this.setArgument(argnum, new Byte(b),Byte.TYPE);
  }
  public int setArgument(char c) {
    return this.setArgument(argc, new Character(c), Character.TYPE);
  }
  public int setArgument(int argnum, char c) {
    return this.setArgument(argnum, new Character(c),Character.TYPE);
  }
  public int setArgument(int i) {
    return this.setArgument(argc, new Integer(i), Integer.TYPE);
  }
  public int setArgument(int argnum, int i) {
    return this.setArgument(argnum, new Integer(i), Integer.TYPE);
  }
  public int setArgument(short s) {
    return this.setArgument(argc, new Short(s), Short.TYPE);
  }
  public int setArgument(int argnum, short s) {
    return this.setArgument(argnum, new Short(s), Short.TYPE);
  }
  public int setArgument(long l) {
    return this.setArgument(argc, new Long(l), Long.TYPE);
  }
  public int setArgument(int argnum, long l) {
    return this.setArgument(argnum, new Long(l), Long.TYPE);
  }
  public int setArgument(float f) {
    return this.setArgument(argc, new Float(f), Float.TYPE);
  }
  public int setArgument(int argnum, float f) {
    return this.setArgument(argnum, new Float(f), Float.TYPE);
  }
  public int setArgument(double d) {
    return this.setArgument(argc, new Double(d), Double.TYPE);
  }
  public int setArgument(int argnum, double d) {
    return this.setArgument(argnum, new Double(d), Double.TYPE);
  }
  public int setArgument(Object obj) {
    return this.setArgument(argc, obj, obj.getClass());
  }
  public int setArgument(int argnum, Object obj) {
    return this.setArgument(argnum, obj, obj.getClass());
  }
  public int setArgument(int argnum, Object obj, Class c) {
    if (argnum >= args.length) {
      argc = argnum + 1;
      Class[] clExpanded = new Class[argc];
      Object[] argsExpanded = new Object[argc];
      System.arraycopy(cl, 0, clExpanded, 0, cl.length);
      System.arraycopy(args, 0, argsExpanded, 0, args.length);
      cl = clExpanded;
      args = argsExpanded;
    }
    args[argnum] = obj;
    cl[argnum] = c;
    return argnum;
  }
}

Back to Article

Listing Four

import java.lang.reflect.InvocationTargetException;import java.util.Vector;


</p>
public class InvokerTest {


</p>
  public void singleInteger(Integer i) {
    System.out.println("in method singleInteger() : i = " + i);
  }
  public void intOnly(int i) {
    System.out.println("in method intOnly() : i = " + i);
  }
  public void arrayTest(byte[] b) {
    System.out.println("in method arrayTest()");
    System.out.println("String from byte array is " + new String(b));
  }
  public void multi(int i, String s, Vector v) {
    System.out.println("in method multi()");
    System.out.println("s = " + s);
    System.out.println("i = " + i);
    System.out.println("v has " + v.size() + " elements");
  }
  public static void main(String args[]) {
    try {
      InvokerTest myInvoker = new InvokerTest();
      ArgumentHolder a1 = new ArgumentHolder();
      a1.setArgument(0,new Integer(1));
      Invoker.dynaCall(myInvoker, "singleInteger", a1);
      ArgumentHolder a2 = new ArgumentHolder();
      int i = 1;
      a2.setArgument(0,i);
      Invoker.dynaCall(myInvoker, "intOnly", a2);
      ArgumentHolder a3 = new ArgumentHolder();
      byte[] b = new String("abcde").getBytes();
      a3.setArgument(b);
      Invoker.dynaCall(myInvoker, "arrayTest", a3);
      ArgumentHolder am = new ArgumentHolder();
      i = 25;
      am.setArgument(i);
      am.setArgument("this is a test");
      Vector vv = new Vector();
      vv.addElement("a");
      vv.addElement("b");
      vv.addElement("c");
      vv.addElement("d");
      am.setArgument(vv);
      Invoker.dynaCall(myInvoker, "multi", am);
    }
    catch (IllegalAccessException e) {
      System.out.println(e);
    }
    catch (InvocationTargetException e) {
      System.out.println(e);
    }
    catch (NoSuchMethodException e) {
      System.out.println(e);
    }
    System.exit(0);
  }
}

Back to Article


Copyright © 1998, Dr. Dobb's Journal


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.