PackageCom.hero;ImportJava.lang.reflect.Field; Public classTestReflction5 { Public Static voidMain (string[] args) {Hero h=NewHero (); //Modify the value of name by using the traditional method GareenH.name = "Gareen"; Try { //Gets the field of the class hero named NameField f1= H.getclass (). GetField ("name"); //Modify the value of this fieldF1.set (H, "Teemo"); //Print the modified valueSystem.out.println (h.name); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
The difference between GetField and Getdeclaredfield: (both methods are used to get the field)
GetField can only get public, including fields that inherit from the parent class.
Getdeclaredfield can get all fields of this class, including private, but cannot get inherited fields. ( Note: Only private fields can be obtained here , but the value of the private field is not accessible )
Lesson five Java reflection Get object properties and methods