问题描述
我有一个Class对象,我想调用一个静态方法.我有以下代码.
I have a Class object and I want to invoke a static method. I have the following code.
Method m = cls.getMethod("main", String[].class);
System.out.println(m.getParameterTypes().length);
System.out.println(Arrays.toString(m.getParameterTypes()));
System.out.println(m.getName());
m.invoke(null, new String[]{});
此打印:
1
[class [Ljava.lang.String;]
main
但是随后它抛出:
IllegalArgumentException: wrong number of arguments
我在这里俯瞰什么?
推荐答案
您将不得不使用
m.invoke(null, (Object)new String[]{});
调用(Object,Object ...)
方法接受 Object ...
.(更正)传递的 String []
数组用作该 Object []
且为空,因此没有要传递给您的元素方法调用.通过将其强制转换为 Object
,您可以说这是包装 Object []
中的唯一元素.
The invoke(Object, Object...)
method accepts a Object...
. (Correction) The String[]
array passed is used as that Object[]
and is empty, so it has no elements to pass to your method invocation. By casting it to Object
, you are saying this is the only element in the wrapping Object[]
.
这是因为数组协方差.你可以做
This is because of array covariance. You can do
public static void method(Object[] a) {}
...
method(new String[] {});
因为 String []
是 Object []
.
System.out.println(new String[]{} instanceof Object[]); // returns true
或者,您也可以将 String []
包裹在 Object []
Alternatively, you can wrap your String[]
in an Object[]
m.invoke(null, new Object[]{new String[]{}});
然后,该方法将使用 Object []
中的元素作为方法调用的参数.
The method will then use the elements in the Object[]
as arguments for your method invocation.
这篇关于为什么通过反射调用main时参数个数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!