Why do I have the wrong number of arguments when calling the main reflection?

I have a class object and I want to call 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[]{}); 

Fingerprints:

  • 1
  • [class [Ljava.lang.String;]
  • Main

But then he throws:

 IllegalArgumentException: wrong number of arguments 

What am I not seeing here?

+6
source share
2 answers

You will need to use

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

The invoke(Object, Object...) method accepts Object... (Correction) The String[] array that is used is used as Object[] and is empty, so it has no elements to jump to the method call. Dropping it on an Object , you say that this is the only element in the wrapper of Object[] .

This is due to covariance of the array. You can do

 public static void method(Object[] a) {} ... method(new String[] {}); 

Since a String[] is an Object[] .

 System.out.println(new String[]{} instanceof Object[]); // returns true 

Alternatively, you can wrap String[] in Object[]

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

The method will then use the elements in Object[] as arguments to invoke the method.

Cautiously using a StackOverflowError call to main(..) .

+9
source

And you can do this:

 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()); String[] a = new String[1]; m.invoke(null,a); 
0
source

All Articles