Invoking a Named Method

Example 9-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 specified arguments. The actionPerformed( ) method does the same thing. If you’ve read Chapter 11, 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). 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 Command class also implements the InvocationHandler interface, which we’ll learn about in the next section.)

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 11. Note that the parse( ) method uses the Tokenizer interface and CharSequenceTokenizer class defined in Chapter 2.

Java does not allow methods to be ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.