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[]{});
This prints:
- 1
- [class [Ljava.lang.String;]
- main
But then it then it throws:
IllegalArgumentException: wrong number of arguments
What am I overlooking here?
And you can do this:
You will have to use
The
invoke(Object, Object...)
method accepts aObject...
. (Correction) TheString[]
array passed is used as thatObject[]
and is empty, so it has no elements to pass to your method invocation. By casting it toObject
, you are saying this is the only element in the wrappingObject[]
.This is because of array covariance. You can do
Because a
String[]
is aObject[]
.Alternatively, you can wrap your
String[]
in anObject[]
The method will then use the elements in the
Object[]
as arguments for your method invocation.Careful with the StackOverflowError of calling
main(..)
.