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

纵然是瞬间 提交于 2019-12-30 18:33:19

问题


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?


回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/22022368/why-do-i-have-the-wrong-number-of-arguments-when-calling-main-through-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!