问题
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