First we need to know what a class object is: A Class object is an object that records the construction methods, properties, methods of a class itself.
1. Three ways to get class objects
Class.forName (' Full class name ')
Class name.
New class name (). GetClass ()
Example: Create a new object with reflection.
Packagereflection;ImportJava.lang.reflect.Constructor;ImportDealreflect. Hero; Public classtestreflection { Public Static voidMain (string[] args) {Try { //create an object using reflectionString className = "Dealreflect. Hero "; //Class ObjectClass pclass=Class.forName (className); //ConstructorsConstructor c=Pclass.getconstructor (); //instantiated by ConstructorHero h2=(Hero) c.newinstance (); H2.name= "Gareen"; System.out.println (H2); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}2. Methods inside the Reflection class
1. Load Class Clazz = Class.forName ("Full class name")
2. Loading Methods method = Clazz.getmethod ("Method name", String.class,int.class (parameter type))
3. Run method Method.invoke (instance of class, pass parameter)
Notice that there is an instance of the class, and the class object is not.
Reflection Main () method
1. Load Class Clazz = Class.forName ("Full class name")
2. Loading Methods method = Clazz.getmethod ("main", string[] args);
3. Operating method, compare strange Method.invoke (Null,new object[] (new string[]{"AA", "BB"}) or Method.invoke (null, Object (new string[]{"AA" , "BB"}))
Because when you pass a string array to the main function, the program splits itself into string a1,string A2
3. Fields inside the Reflection class
1. Load Class Clazz = Class.forName ("Full class name")
[Clazz.setaccessible (true)] for violent reflection, you can get the value of the private property or method.
2. load fields field F = Clazz.getfield ("Field name")
Remark: The difference between GetField and Getdeclaredfield
Both of these methods are used to get the field
GetField can only get public, including fields that inherit from the parent class.
Getdeclaredfield can get all the fields of this class,includes private, but cannot get inherited fields. ( Note: Only private fields can be obtained here , but the value of the private field cannot be accessed unless setaccessible (true) is added)
3. Get the value of a field
String name = (stirng) f.get (p)
or Object value = F.get (p)
4. Get the type of the field
Class type = F.gettype ();
5. Set the value of a field
F.set (P, "xxxxxxxx")
Summary of the Java reflection mechanism