1. Opening
The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.
2. Reflection Test Class
Package Reflectdemo;public class Test {public test () {System.out.println ("constract");} Public test (String str,int type) {System.out.println ("str:" +str+ "type:" +type);} public int id;public String name;public void Printname () {System.out.print ("Dirk.wang");} public static void Printlol () {System.out.print ("King.qwiner");} Private void privatefun (String key) {System.out.println (key);} Public void publicfun (String key) {System.out.println (key);}}
3. Calling classes by reflection
Package Reflectdemo;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;public class ReflectClass {public static void Main (string[] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, Exception, SecurityException, IllegalArgumentException, invocationtargetexception {//TODO auto-generated method Stubreflect ();} public static void reflect () throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, Nosuchmethodexception, SecurityException, IllegalArgumentException, InvocationTargetException, nosuchfieldexception{//gets the class C=class.forname ("Reflectdemo.test");//Instantiate the default parameterless constructor Object obj =c.newinstance (); Gets all methods in the class (not including private) method[] M =c.getmethods (); For (method Method:m) {System.out.println (method);} Get all methods including Private method method[] All=c.getdeclaredmethods (); For (method Method:all) {System.out.println (method);} Gets the classA specified method (specifying the method name and parameter type) Fun=c.getmethod ("Printlol"); Call the method Fun.invoke (obj) without parameters; Method Paramerfun=c.getmethod ("Publicfun", String.class) is obtained with parameters. Call the method with parameters Paramerfun.invoke (obj, "dirk.wang_paramerfun"); Gets the fields in the class (excluding private fields) field[] Fields=c.getfields (); for (field Field:fields) {System.out.println (field);} Gets the specified field and assignment field Field1=c.getfield ("id"); Field1.set (obj, 2017); System.out.println (Field1.get (obj)); Instantiate a constructor with parameters Class Cl=class.forname ("Reflectdemo.test"); Create a constructor with parameters Constructor Ct=cl.getconstructor (string.class,int.class); Instantiate the constructor test t= (Test) ct.newinstance ("Dirk", 2017); T.printlol (); }}
Java reflection mechanism