Why do I have the wrong number of arguments when calling main through reflection?
You will have to use
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[] {});
Because a String[]
is a Object[]
.
System.out.println(new String[]{} instanceof Object[]); // returns true
Alternatively, you can wrap your String[]
in an Object[]
m.invoke(null, new Object[]{new String[]{}});
The method will then use the elements in the Object[]
as arguments for your method invocation.
Careful with the StackOverflowError of calling main(..)
.