iar*_*gin 25 java reflection illegalargumentexception
我有一个类AClass和一个方法someMethod,将Object数组作为参数.
public class AClass {
public void someMethod(Object[] parameters) {
}
}
Run Code Online (Sandbox Code Playgroud)
在main中,当我尝试在我创建的对象上调用此方法并将对象数组作为此方法的参数时
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);
Run Code Online (Sandbox Code Playgroud)
我得到"错误的参数数量错误".我错过了什么?
bia*_*oqi 23
那没关系.
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);
Run Code Online (Sandbox Code Playgroud)
注意invoke方法的第二个参数.它是Object []本身,方法的参数类型也是Object [].
rua*_*akh 12
对orien和biaobiaoqi所说的话进行了扩展...
你在这里可能会让人感到困惑的是,Method.invoke(Object, Object...)通常可以把参数称为"内联",可以这么说; 当编译器看到类似的内容时someMethod.invoke(someObject, arg1, arg2),它会隐式创建一个数组new Object[]{arg1, arg2},然后将该数组传递给它Method.invoke.Method.invoke然后将该数组的元素作为参数传递给您正在调用的方法.到现在为止还挺好.
但是当编译器看到类似的东西时someMethod.invoke(someObject, someArray),它假定你已经将参数打包到数组中; 所以它不会再重新包装它们.那么接下来Method.invoke会尝试将通过要素的someArray作为参数传递给方法调用的,而不是将someArray 自身作为一个参数.
(这始终是如何...表示法的工作原理,它接受任一含有适当类型的元素,阵列或.零或适当类型的多个参数)
因此,正如orien和biaobiaoqi所说的那样,你需要将你的数据重新包装parameters成一个额外的数组new Object[] {parameters},这样它parameters本身最终会传递给你的方法.
那有意义吗?
Method.invoke方法使对象接收方法调用以及方法的参数数组.由于您的方法采用一个参数,因此给定的数组大小必须为1.
尝试创建一个大小为1的新数组:
someMethod.invoke(anObject, new Object[] {parameters});
Run Code Online (Sandbox Code Playgroud)
请注意,此数组中的一个值可以为null.这将模拟anObject.someMethod(null)