我现在有这样的代码:
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);发布于 2018-06-20 15:36:39
就像评论说的。我们不知道哪种方法是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文档方法从来没有排序过
返回数组中的元素没有排序,也没有按任何特定顺序排序。
因此,有时您的代码可能工作,有时不起作用。
发布于 2018-06-20 15:40:30
结果是,当我使用getMethods()[0]时,我得到了主方法并调用它,这个方法显然没有参数,所以不能工作。理想情况下我应该用
getMethod("eat", long.class, double.class, String.class)这是有用的。
https://stackoverflow.com/questions/50951861
复制相似问题