![](/img/trans.png)
[英]method.invoke generates IllegalArgumentException:wrong number of arguments
[英]Wrong number of arguments on method.invoke
我目前有这个代码:
public class Pants {
public static void main(String[] args) {
Pants pants = new Pants();
pants.eat(10, 10.3, "Nice.");
Object[] params = {(long)10, 10.3, "Nice."};
Method eatMethod = pants.getClass().getMethods()[0];
try
{
eatMethod.invoke(pants, params);
} catch (IllegalAccessException | InvocationTargetException e)
{
e.printStackTrace();
}
}
public void eat(long amount, double size, String name) {
System.out.println("You ate");
}
}
它总是抛出
IllegalArgumentException: wrong number of arguments.
这也发生在其他方法中。 我在eat()
使用了与method.invoke
相同的参数,并且类型相同。 错误被抛出
eatMethod.invoke(pants, params);
正如评论所说。 我们不知道pants.getClass().getMethods()[0]
方法是pants.getClass().getMethods()[0]
。 尝试使用eatMethod.getName()
获取名称,看看是否真的是方法eat。 如果没有,你可以试试这个。
java.lang.reflect.Method method;
method = pants.getClass().getMethod("eat", Long.class, Double.class, String.class);
.
.
.
method.invoke(pants,params );
另外...检查Java文档这些方法从不排序
返回的数组中的元素没有排序,也没有任何特定的顺序。
因此,有时您的代码可能有效,有时则无效。
事实证明,当我使用getMethods()[0]
,我正在获取 main 方法并调用它,它显然没有参数,所以它不起作用。 理想情况下我应该使用
getMethod("eat", long.class, double.class, String.class)
这确实有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.