我正在尝试运行以下代码:
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");
}
}
我不断收到 IllegalArgumentException:错误数量的参数,即使这两种方法都不带参数。
我尝试将 null
传递给 invoke
方法,但这会引发 NPE。
最佳答案
您实际上是在正确地调用方法,问题是 Class.getMethods() 方法返回类中的所有方法,包括从父类(super class)继承的方法,例如本例中的 Object。 documentation状态:
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
例如,在这种情况下,您最终可能会在没有任何参数的情况下调用 Object.equals。 Object.wait 方法等也是如此。
关于java - 非法参数异常 : wrong number of arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445771/