The previous article reflected the member method of the class, and the main method should also be included, because the main method is a static method.
But the actual Mian reflection is slightly different, the reason is mainly to maintain 1.5 compatible 1.4 version during the upgrade process: reasoning as follows
1. The parameter of the main method is a parameter of type string[]
2, 1.5 support variable parameters, so it can be variable parameter form to read the parameters,
such as: Main (string[]{"Arg1", "Arg2"}) ===>
Main ("Arg1", "arg2")
3, but in 1.4, does not support variable parameters, so will not be decomposed, directly as the main (string[]{"Arg1", "AREG2"})
4, for compatibility with 1.4 version, the main method is still only receive a parameter type string[] parameter
Combine the above:
When you pass in the string["arg0", "arg1", the 1.5 version will be resolved to: Two parameter values are "arg0", "arg1" parameters
A parameter that only receives a string[] type with the main method does not conform.
There are two ways to handle this:
1. Pass in an array and put string[] in the array: New object[]{new string[]{"Arg1", "Arg2"}}
2. Convert an array to an object
The test generation file is as follows:
Mian Method:
1 Package Cn.rt.gwq; 2 3 Public class maintest {4 5 Public Static void Main (string[] args) {6 System.out.println ("Main run ..."); 7 }89 }
Demo test Method:
1 PackageCn.rt.gwq;2 3 ImportJava.lang.reflect.Method;4 5 Public classDemo_mainrflt {6 7 Public voidTest ()throwsexception{8 9Class clazz = Class.forName ("Cn.rt.gwq.mainTest");Tenmethod = Clazz.getmethod ("main", string[].class); One //method One: Put an array inside the array AMethod.invoke (NULL,Newobject[]{Newstring[]{"arg0", "Arg1"}}); - //method Two: Cast the array into object -Method.invoke (NULL, (Object)Newobject[]{"arg0", "Arg1"}); the - } - -}
Anatomy of Java Reflection Main method