[英]IllegalArgumentException: wrong number of arguments
I'm trying to run the following code: 我正在尝试运行以下代码:
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");
}
}
I keep getting an IllegalArgumentException: wrong number of arguments, even though the two methods take no arguments. 我一直得到一个IllegalArgumentException:错误的参数数量,即使这两个方法没有参数。
I tried passing null
to the invoke
method, but that throws a NPE. 我尝试将null
传递给invoke
方法,但是抛出了一个NPE。
You are actually invoking the methods correctly, the problem is that the Class.getMethods() method returns ALL methods in the class, INCLUDING those inherited from super classes, such as Object in this case. 您实际上正在调用方法,问题是Class.getMethods()方法返回类中的ALL方法,包括从超类继承的方法,例如本例中的Object。 The documentation states: 文件说明:
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. 返回一个包含Method对象的数组,这些对象反映此Class对象所表示的类或接口的所有公共成员方法,包括由类或接口声明的那些以及从超类和超接口继承的那些。
In this case you might end up calling Object.equals without any arguments, for example. 在这种情况下,您可能最终调用Object.equals而不使用任何参数。 The same goes for the Object.wait methods etc. Object.wait方法等也是如此。
According to documentation : 根据文件 :
If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null. 如果基础方法所需的形式参数的数量为0,则提供的args数组的长度可以为0或null。
Have you tried this? 你试过这个吗?
m.invoke(cls, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.