IllegalArgumentException:参数数量错误
我正在尝试运行以下代码:
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。
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.
I tried passing null
to the invoke
method, but that throws a NPE.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上正确地调用了这些方法,问题是 Class.getMethods() 方法返回类中的所有方法,包括从超类继承的方法,例如本例中的 Object。 文档指出:
例如,在这种情况下,您可能最终会调用不带任何参数的 Object.equals。 Object.wait 方法等也是如此。
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. The documentation states:
In this case you might end up calling Object.equals without any arguments, for example. The same goes for the Object.wait methods etc.
根据 文档:
你试过这个吗?
According to documentation:
Have you tried this?