我正在尝试运行以下代码:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflection {
/**
* @param args
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalAccessException,
InvocationTargetException, IllegalArgumentException {
Class<Cls> cls = Cls.class;
Method[] methods = cls.getMethods();
for (Method m : methods) {
m.invoke(cls);
}
}
}
class Cls {
public static void method1() {
System.out.println("Method1");
}
public static void method2() {
System.out.println("Method2");
}
}
Run Code Online (Sandbox Code Playgroud)
我一直得到一个IllegalArgumentException:错误的参数数量,即使这两个方法没有参数.
我尝试传递null给invoke方法,但是抛出了一个NPE.