Java 反射 API 为您提供了一种方法,可以将 Method 类型的对象与目标对象一起传递,然后可以在目标对象上调用该方法。
示例如下:
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
}