Passing a Method reference to a method and then invoking the method with parameters.
有多种方法可以做到这一点。此说明性示例使用名为 myMethod 的静态方法,将一个对象作为参数。
import java.lang.reflect.Method;
public class Tester54 {
static public class J42 {
static public Object myMethod(final Object o) {
return "Wow:" + o.toString();
}
}
private static void
doIt(final Class<?> c, final Method m, final Class<?>[] types, final Object[] args)
throws Exception {
final Object s = m.invoke(J42.class, new Object[] { "wow" });
System.out.println(s);
}
public static void main(final String[] a) throws Exception {
final Method m = J42.class.getMethod("myMethod", new Class<?>[] { Object.class });
final Class<?>[] types = new Class[] { Object.class };
final Object[] args = new Object[] { "wow" };
doIt(J42.class, m, types, args);
}
}