Java Reference
In-Depth Information
Example 8−1: ShowClass.java (continued)
parameters = c.getParameterTypes();
exceptions = c.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) +
typename(c.getDeclaringClass()) + "(");
}
for(int i = 0; i < parameters.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print(typename(parameters[i]));
}
System.out.print(")");
if (exceptions.length > 0) System.out.print(" throws ");
for(int i = 0; i < exceptions.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print(typename(exceptions[i]));
}
System.out.println(";");
}
}
Invoking a Named Method
Example 8-2 defines the
Command
class, which demonstrates another use of the
Reflection API. A
Command
object encapsulates a
Method
object, an object on which
the method is to be invoked, and an array of arguments to pass to the method.
The
invoke()
method invokes the method on the specified object using the speci-
fied arguments. The
actionPerformed()
method does the same thing. If you've
read Chapter 10,
Graphical User Interfaces
, you know that this method implements
the
java.awt.event.ActionListener
interface, which means that
Command
objects
can be used as action listeners to respond to button presses, menu selections, and
other events within a graphical user interface. GUI programs typically create a
slew of
ActionListener
implementations to handle events. With the
Command
class,
simple action listeners can be defined without creating lots of new classes.
The most useful feature (and the most complicated code) in the
Command
class is
the
parse()
method, which parses a string that contains a method name and list of
arguments to create a
Command
object. This is useful because it allows
Command
objects to be read from configuration files, for example. We'll use this feature of
the
Command
class in Chapter 10.
Java does not allow methods to be passed directly as data values, but the Reflec-
tion API makes it possible for methods passed by name to be invoked indirectly.
Note that this technique is not particularly efficient. For asynchronous event han-
dling in a GUI, though, it is certainly efficient enough: indirect method invocation
through the Reflection API is much faster than the response time required by the
limits of human perception. Invoking a method by name is not an appropriate
technique, however, when repetitive calls are required or when the computer is
not waiting for human input. Thus, you should not use this technique for passing
a comparison method to a sorting routine or passing a filename filter to a directory
listing method, for example. In cases like these, you should use the standard tech-
nique of implementing a class that contains the desired method and passing an
instance of the class to the appropriate routine.