Actions and Reflection

Example 11-15 demonstrated the use of Action objects, which allow an application’s command set to be easily presented to the user in menubars, toolbars, and so on. The awkward part about working with Action objects, however, is that each one must usually be defined as a class of its own. If you are willing to use the Java Reflection API, however, there is an easier alternative. In Example 9-2 we saw the Command class—a class that encapsulates a java.lang.reflect.Method object, an array of arguments for the method, and the object upon which the method is to be invoked. Calling the invoke( ) method of a Command object invokes the method. The most powerful feature of the Command class, however, is its static parse( ) method, which can create a Command by parsing a textual representation of the method name and argument list.

The Command class implements the ActionListener interface, so Command objects can be used as simple action listeners. But a Command is not an Action. Example 11-16 addresses this; it is a listing of CommandAction.java, a subclass of AbstractAction that uses a Command object to perform the action. Since the Command class does the hard work, the code for CommandAction is relatively simple.

Example 11-16. CommandAction.java

package je3.gui; import je3.reflect.*; import javax.swing.*; import java.awt.event.*; public class CommandAction extends AbstractAction { Command command; // The command to execute in response to an ActionEvent /** ...

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.