What is wrong with my Method.invoke call?

你。 提交于 2019-12-22 01:48:28

问题


I just created the following minimalistic testcase:

package testcase;

public class Main
{

    public static void main( String[] args )
        throws Throwable
    {
        if ( args.length == 0 )
            Main.class.getMethod( "main", String[].class ).invoke( null, new String[] { "test" } );
    }

}

It should just run, with no output and no exception. The main method should be calling itself using reflection. However I get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at testcase.Main.main(Main.java:10)

And I cannot figure out, why...


回答1:


Use

public static void main(String[] args) throws Throwable {
    if (args.length == 0)
        Main.class.getMethod("main", String[].class)
                  .invoke(null, new Object[] {new String[] { "test" }});
}

The problem is that invoke has vararg parameter which could be either array or plain list of objects and Java arrays are covariant. So .invoke(null, new String[] { "test" }) is interpreted by compiler in the same way as .invoke(null, new Object[] { "test" }). You should have compiler warning about this ambiguity.




回答2:


Cast new String[] { "test" } in a new Object[] {}.



来源:https://stackoverflow.com/questions/36125950/what-is-wrong-with-my-method-invoke-call

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