我的Method.invoke调用出了什么问题?

Ste*_*eil -1 java reflection exception invocation java-8

我刚刚创建了以下简约测试用例:

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

}
Run Code Online (Sandbox Code Playgroud)

它应该只运行,没有输出,也没有例外.该main方法应该使用反射来调用自身.但是我得到以下异常:

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)
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚,为什么......

Tag*_*eev 8

使用

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" }});
}
Run Code Online (Sandbox Code Playgroud)

问题是invokevararg参数可以是数组或普通的对象列表,Java数组是协变的.所以.invoke(null, new String[] { "test" })编译器以同样的方式解释.invoke(null, new Object[] { "test" }).您应该有关于这种歧义的编译器警告.

  • 使用`invoke(null,(Object)(new String [] {"test"}))`也应该工作,AFAIK. (3认同)