为什么Class#getDeclaredMethods0在尝试调用main时失败?

时间:2015-03-03 15:17:15

标签: java reflection

为什么此代码段会因IllegalArgumentException: wrong number of arguments失败?演示代码适用于普通成员和静态方法,以及本机声明的代码......

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

1 个答案:

答案 0 :(得分:2)

我们不清楚为什么你通过反思调用getDeclaredMethods,但main的调用被打破了,因为你试图把它称之为就好了多个String参数 - args中每个值一个。相反,您希望传递类型为String[]单个参数。你可以这样做:

main.invoke(null, new Object[] { args });