Tom*_*Tom 7 java reflection parameters exception
我必须错过一些非常基本的东西 当我尝试在方法调用期间传递任何类型的数组时,我收到错误.但是,当我这样做时,它通常会起作用.
这是失败的完整代码
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
// Normal
MyClass.sayHello(new String[] {"StackOverflow"});
// Reflection
Method m = MyClass.class.getMethod("sayHello", String[].class);
m.invoke(null, new String[]{"StackOverflow"});
}
static class MyClass {
public static void sayHello(String[] args) {
System.out.println("Hello " + args[0]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
抛出异常
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:497)
at Main.main(Main.java:11)
Run Code Online (Sandbox Code Playgroud)
String... 顺便说一下也行不通.
问题是第二个参数invoke是一个参数数组 - 你只是指定一个参数.
在大多数情况下,第二个参数Method.invoke是varargs参数是可以的,但由于你的参数已经是一个兼容的数组Object[],编译器不会创建一个包装器数组.我希望你得到这样的编译时警告:
Main.java:11: warning: non-varargs call of varargs method with inexact argument type for
last parameter;
m.invoke(null, new String[]{"StackOverflow"});
^
cast to Object for a varargs call
cast to Object[] for a non-varargs call and to suppress this warning
Run Code Online (Sandbox Code Playgroud)
您可以显式创建一个包装参数的数组,或者将参数强制转换Object为编译器需要自己包装它:
// Creates the wrapper array explicitly
m.invoke(null, new Object[] { new String[] { "StackOverflow" } });
Run Code Online (Sandbox Code Playgroud)
要么
// Compiler creates the wrapper array because the argument type is just Object
m.invoke(null, (Object) new String[] { "StackOverflow" });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
976 次 |
| 最近记录: |