且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么通过反射调用main时参数个数错误?

更新时间:2023-11-30 21:28:46

您将不得不使用

m.invoke(null, (Object)new String[]{});

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(..).