Java Reflection

With the JDK 1.1 Reflection API, you can not only discover the fields, methods and constructors of loaded classes, but also dynamically manipulate them within the basic security framework. Chris Howard adds a note on the relationship between reflection and JavaBeans.


January 01, 1998
URL:http://www.drdobbs.com/jvm/java-reflection/184410463

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:

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:

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:

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 {


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;

ReflectionDemo myClient = new ReflectionDemo();

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;


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;


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); }

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;


public class InvokerTest {

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

Dr. Dobb's Journal January 1998: Java Reflection

Java Reflection

By Chris Howard

Dr. Dobb's Journal January 1998

public String methSubtract(int i1, int i2) {
   return Integer.toString(i1) + " - " +
     Integer.toString(i2) + " = " + Integer.toString(i1 - i2);
}

Example 1: Adding a subtract command.


Copyright © 1998, Dr. Dobb's Journal

Dr. Dobb's Journal January 1998: Reflecting on Beans

Reflecting on Beans

Dr. Dobb's Journal January 1998

By Chris Howard


JavaBeans, the platform-neutral component architecture for Java, was added in JDK 1.1. In the Windows world, a Java Bean is similar to an OCX or VBX control. A Bean is reusable and can be visually manipulated in a software-development tool such as Borland's JBuilder, IBM's VisualAge for Java, Sun's Java Workshop, Sybase's PowerJ, Symantec's Visual Cafe, and, to some extent, Microsoft's Visual J++. But how do those tools know how to manipulate a Bean? They do it through a process known as "reflection."

In the past, a software component might publish an API in a separate definition file or use some other technique to inform an application of its interface: A Bean-aware application uses the Java Core Reflection API instead. This lets an application dynamically read the class and method definitions directly from the binary class file. With reflection, you can acquire interfaces and instances for any other object. Without reflection, JavaBeans wouldn't be possible.

The Java Core Reflection API is a low-level interface, and while it can be used directly, there are some pitfalls. Determining a valid method for a Bean can be subject to some interpretation by third-party applications. An easier (and better) way to inspect Bean properties is the Introspector class, which uses the Reflection API internally to do its work.

The Introspector class understands Beans completely, so it won't make any mistakes interpreting Bean methods and properties. If all applications use the Introspector class to get a Bean's interface, they will all expose a consistent representation of the Bean's methods. The main function of the Introspector class is to return a BeanInfo class for any Bean passed as an argument to one of two getBeanInfo(bean) methods. One method merges all BeanInfo descriptions of every parent of the specified Bean; the other method lets you specify a class beyond which introspection should be ignored. Remember that every Java class is a legal Bean, so the inheritance chain could be quite long if you don't stop it. Eventually, it will stop at the Object class.

If a Bean does not specify a BeanInfo class, then one will be constructed automatically by the Introspector class and returned. Most Beans designed for third-party use in a Java IDE will implement a BeanInfo object. The information in a BeanInfo includes property, event, set, and method descriptors, as well as default values, and even a Bean icon that can be used by the IDE to represent the Bean.

You don't have to be writing an IDE to make use of the Introspector class. Any application can be a container for JavaBeans. This means you can structure your program in such a way that your application examines Beans, and can determine their use on the fly. A paint program, for instance, could implement drawing objects and graphics file formats as Beans. For your Java applications, it's something to reflect on.

-- C.H.


Copyright © 1998, Dr. Dobb's Journal

Dr. Dobb's Journal January 1998: Java Reflection

Java Reflection

By Chris Howard

Dr. Dobb's Journal January 1998

Table 1: Valid commands.


Copyright © 1998, Dr. Dobb's Journal

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.