调用方法时参数数量错误 [英] Wrong number of arguments error when invoking a method
本文介绍了调用方法时参数数量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 AClass
类和一个方法 someMethod
,它获取一个 Object
数组作为参数.
I have class AClass
and a method someMethod
that gets an Object
array as parameter.
public class AClass {
public void someMethod(Object[] parameters) {
}
}
在main中,当我尝试在我创建的对象上调用此方法并将对象数组作为该方法的参数时
In main, when I try to invoke this method on the the object that I have created and give an object array as a parameter to this method
Object[] parameters; // lets say this object array is null
Class class = Class.forName("AClass");
Object anObject = class.newInstance();
Method someMethod = class.getDeclaredMethod("someMethod", parameters.getClass());
someMethod.invoke(anObject, parameters);
我收到错误数量的参数错误".我错过了什么?
I get "wrong number of arguments error". What am i missing?
推荐答案
没关系.
Object[] parameters = {new Object()}; // lets say this object array is null
Class clas = Class.forName("AClass");
Object anObject = clas.newInstance();
Object[] param = {parameters};
Method someMethod = clas.getDeclaredMethod("someMethod", parameters.getClass());
someMethod.invoke(anObject, param);
注意调用方法的第二个参数.它是 Object[]
本身,你的方法的参数类型也是 Object[]
.
Be careful about the second parameter of the invoke method. It's Object[]
itself, and the argument type of your method is Object[]
too.
这篇关于调用方法时参数数量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文