[英]Why does Class#getDeclaredMethods0 fail when trying to invoke main?
Why does this code snippet fail with IllegalArgumentException: wrong number of arguments
? 为什么此代码片段会因
IllegalArgumentException: wrong number of arguments
失败IllegalArgumentException: wrong number of arguments
? Demonstrated code works with ordinary member and static methods, as well as with native declared ones... 演示的代码可与普通成员和静态方法以及本机声明的方法一起使用...
public class Program {
public static void main(String[] args) throws ReflectiveOperationException {
//get native getDeclaredMethods method
Method Class$getDeclaredMethods0 = Class.class.getDeclaredMethod("getDeclaredMethods0", boolean.class);
Class$getDeclaredMethods0.setAccessible(true);
//call main
Method[] methods = (Method[]) Class$getDeclaredMethods0.invoke(Program.class, false);
Method main = methods[0];
main.invoke(null, args); // ← Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
//at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
//at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
//at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
//at java.lang.reflect.Method.invoke(Method.java:606)
//at Program.main(Program.java:19)
//at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
//at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
//at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
//at java.lang.reflect.Method.invoke(Method.java:606)
//at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
}
}
It's not clear why you're calling getDeclaredMethods
via reflection, but the invocation of main
is broken because you're trying to call it as if it had several String
parameters - one per value in args
. 目前尚不清楚为什么要通过反射调用
getDeclaredMethods
,但是对main
的调用已中断,因为您试图像具有多个String
参数一样对其进行调用-每个args
值一个。 Instead, you want to pass a single argument, of type String[]
. 相反,你想传递一个参数,类型
String[]
You can do that like this: 您可以这样做:
main.invoke(null, new Object[] { args });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.