Network analysis of 1.Java reflection mechanism
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; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.
2. Practical Application
Many times, after we instantiate a class and want to change its properties, programmers often privatize some of the properties, including some methods, and then we can use the Java reflection mechanism to change the property values in this instance, or call these privatized methods
3. Example
First write a class, public class Father {private String name;public Father () {setName ("Peter");} private void SetName (String name) {this.name = name;} Public String GetName () {return name;}}
A test class-no reflection mechanism is used public class child {public static void main (string[] args) { try{ Father father=new Father ();
system.out.println (Father.getname ()); The result is Peter }catch (Exception ex) { ex.printstacktrace ();}} }
The test class, using the reflection mechanism, modifies the variable public class child {public static void main (string[] args) { try{ Father father=new Father (); C2/>class<father> Fatherclass=father.class; Access private variable name Field field=fatherclass.getdeclaredfield ("name"); Set to modify field.setaccessible (true); There are two parameters (need to change an instance of a variable, the value of a variable); Field.set (father, "John"); System.out.println (Father.getname ());//output John }catch (Exception ex) { ex.printstacktrace ();}} }
Call method public class child {public static void main (string[] args) { try{ Father father=new Father (); Class<father> Fatherclass=father.class; method = Fatherclass.getdeclaredmethod ("SetName", string.class); Method.setaccessible (true); Method.invoke (father, "Rose"); System.out.println (Father.getname ());//output John }catch (Exception ex) { ex.printstacktrace ();}} }
It is important to note that the Getdeclaremethod () method and the GetMethod () method
Getdeclaremethod () gets all of its own methods, including public,private,protected
GetMethod () Gets all public methods that include the parent class
The reflection mechanism of Java