The mechanism and implementation of Field object
1. Field Object Overview
1) The Java.lang.reflect.Field class, which is a class used to represent property objects in a class, in an interface.
2) You can manipulate the information for all properties and properties, such as private and public, in a class.
2. Introduction to the common methods of Field objects
Method name |
Interpretation |
GetName () |
Get Property name |
GetType () |
Get Property type |
Get (Object obj) |
Gets the value of this property in the Obj object |
Set (Object obj,object value) |
Assign value to the BoJ property |
Setaccessible (Boolean) |
Enable/disable access control permissions |
PackageCom.rainmer.main;ImportJava.lang.reflect.Field;ImportCom.rainmer.bean.Book; Public classFieldtest {//The method is used to get the properties in the class using the passed class object . Public voidShow (Class C1) {field[] fi= C1.getdeclaredfields ();//can get all properties, public or privateSystem.out.println ("~~~~~~~~~~~~ gets all attributes (including private) ~~~~~~~~~~~~~~"); for(Field ff:fi) {System.out.println (Ff.getname ()); System.out.println (Ff.gettype ()); } System.out.println ("~~~~~~~~~~~~ can only get common attribute ~~~~~~~~~~~~~~"); Field[] Fi1= C1.getfields ();//only common properties can be obtained for(Field ff:fi1) {System.out.println (Ff.getname ());//Property nameSystem.out.println (Ff.gettype ());//Property Type } } //This method is used to get the property and the value of the property using the entity class object passed in . Public voidShow (Object ob) {System.out.println ("~~~~~~~~~~~~~~~ gets the property and the value of the property through the entity class object ~~~~~~~~~~~~~~~~~~~"); Class CL=Ob.getclass (); Field[] fi=Cl.getdeclaredfields (); Try{ for(Field ff:fi) {ff.setaccessible (true);//enable access, not to turn private properties into shared propertiesSystem.out.println (Ff.getname () + "value" +ff.get (ob)); } }Catch(Exception e) {e.printstacktrace (); } } Public Static voidMain (string[] args) {book Bo=NewBook (); Bo.setid (1); Bo.setname ("Fighting the heavens."); Bo.settype (Fantasy); Fieldtest ft=Newfieldtest (); Ft.show (book.class); Ft.show (BO); }}
Operation Result:
Called the SetName method
~~~~~~~~~~~~ get all attributes (including private) ~~~~~~~~~~~~~~
Id
Int
Name
Class Java.lang.String
Type
Class Java.lang.String
~~~~~~~~~~~~ can only get common attributes ~~~~~~~~~~~~~~
Type
Class Java.lang.String
~~~~~~~~~~~~~~~ gets the property and the value of the property through the entity class object ~~~~~~~~~~~~~~~~~~~
ID value 1
Name Value bucket Break Sky
Type value Fantasy
Introduction to the Java Reflection Mechanism 02