Why does Class#getDeclaredMethods0 fail when trying to invoke main?

Why does this code snippet fail with 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)
        }
    }
Jon Skeet
people
quotationmark

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. Instead, you want to pass a single argument, of type String[]. You can do that like this:

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

people

See more on this question at Stackoverflow