Recent research jetty source code, found that the code inside the container can not understand, are all Java syntax, is basically reflective + design mode + configuration file. Very inexplicable wonderful method of calling. There is a call to the main method of reflection, the result is not understood, so we study the reflection function. Because of the reflection of the article on the Internet too much, I mainly studied the main method, private method of the call. as follows, reflection invokes the HelloWorld class method. The HelloWorld classes are as follows:
public class HelloWorld {public
static void Main (string[] args) {
System.out.println ("HelloWorld");
}
private void prt (String msg) {
System.out.println (msg);
}
}
Invoke the Main method as follows:
public class Helloworldrefection {public
static void Main (string[] args) throws Instantiationexception, Illegalaccessexception,
SecurityException, Nosuchmethodexception, IllegalArgumentException, InvocationTargetException {Method Method
= HelloWorld.class.getMethod ("main", String[].class);
Method.invoke (null, (Object) New string[]{});
}
Invoke the private method as follows:
public class Helloworldrefection {public
static void Main (string[] args) throws Instantiationexception, Illegalaccessexception,
SecurityException, Nosuchmethodexception, IllegalArgumentException, invocationtargetexception {
Class clazz = helloworld.class;
HelloWorld HelloWorld = HelloWorld.class.newInstance ();
Method[] methods = Clazz.getdeclaredmethods ();
For (method Method:methods) {
System.out.println (Method.getname ());
if (Method.getname (). Equals ("PRT")) {
method.setaccessible (true);
Method.invoke (HelloWorld, "Hello");}}}
Summarize:
1 Invoking the Main method requires that the main method's argument is string[], but when Method.invoke, the string[is required to be cast to object, and for the reason, many on the web say this, The main is that the JDK executes the main method by dividing the string[] into multiple parameters, and so on. After I analyzed the source code, will be the issue of a special article to write out.
2 Calling the private method requires that before calling this method, you need to set the method of this execution to the following, instead of just finding a place to run the method.setaccessible (true).
3 When a method is invoked dynamically using reflection, it is primarily with the Method.invoke () method, and if it is a static method, the first parameter of invoke is set to NULL, and if it is not a static method, the first argument is set to the object generated by the class.