O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required