我的Method.invoke调用有什么问题? [英] What is wrong with my Method.invoke call?
问题描述
我刚刚创建了以下简约测试用例:
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" } );
}
}
它应该只运行,没有输出,也不例外。 main
方法应该使用反射进行自我调用。但是我得到以下异常:
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...
推荐答案
使用
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" }});
}
问题是调用
具有vararg参数,它可以是数组或对象的简单列表,而Java数组是协变的。因此,编译器以 .invoke(null,new String [] { test})
解释与 .invoke(null,new Object [] { 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.
这篇关于我的Method.invoke调用有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!