Java Reference
In-Depth Information
Example 8−2: Command.java
package com.davidflanagan.examples.reflect;
import java.awt.event.*;
import java.beans.*;
import java.lang.reflect.*;
import java.io.*;
import java.util.*;
/**
* This class represents a Method, the list of arguments to be passed
* to that method, and the object on which the method is to be invoked.
* The invoke() method invokes the method. The actionPerformed() method
* does the same thing, allowing this class to implement ActionListener
* and be used to respond to ActionEvents generated in a GUI or elsewhere.
* The static parse() method parses a string representation of a method
* and its arguments.
**/
public class Command implements ActionListener {
Method m; // The method to be invoked
Object target; // The object to invoke it on
Object[] args; // The arguments to pass to the method
// An empty array; used for methods with no arguments at all.
static final Object[] nullargs = new Object[] {};
/** This constructor creates a Command object for a no-arg method */
public Command(Object target, Method m) { this(target, m, nullargs); }
/**
* This constructor creates a Command object for a method that takes the
* specified array of arguments. Note that the parse() method provides
* another way to create a Command object
**/
public Command(Object target, Method m, Object[] args) {
this.target = target;
this.m = m;
this.args = args;
}
/**
* Invoke the Command by calling the method on its target, and passing
* the arguments. See also actionPerformed() which does not throw the
* checked exceptions that this method does.
**/
public void invoke()
throws IllegalAccessException, InvocationTargetException
{
m.invoke(target, args); // Use reflection to invoke the method
}
/**
* This method implements the ActionListener interface. It is like
* invoke() except that it catches the exceptions thrown by that method
* and rethrows them as an unchecked RuntimeException
**/
public void actionPerformed(ActionEvent e) {
try {
invoke();
// Call the invoke method
}
Search WWH ::




Custom Search