调用方法时错误的参数数量错误 [英] Wrong number of arguments error when invoking a method
本文介绍了调用方法时错误的参数数量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类 AClass
和一个方法 someMethod
获得对象
数组作为参数。
I have class AClass
and a method someMethod
that gets an Object
array as parameter.
public class AClass {
public void someMethod(Object[] parameters) {
}
}
主要是当我尝试调用此方法时我创建的对象并将对象数组作为此方法的参数
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屋!
查看全文