Two ways to access the JavaBean property
1) Call the Bean's Setxxx or getxxx method directly;
2) through introspective technology access (the Java.beans package provides an introspective API), introspective technical access is also available in two ways:
A) The properties of the bean are manipulated through the PropertyDescriptor class;
b) The BeanInfo of the Bean object is obtained through the Introspector class, and then the descriptor (PropertyDescriptor) of the property is obtained through BeanInfo, and the property descriptor is used to obtain a corresponding getter/ Setter methods, and then invoke these methods through the reflection mechanism.
public class person { private string name;//field private string password;//field private Integer age;//field
//a Get or set method is added to the field, it is called the property public String getXxx () { return "AA"; } setter/getter}
The following is an introspective mechanism to manipulate the person object.
Get all the properties of the class
@Test public void Test1 () throws Exception { BeanInfo BeanInfo = introspector.getbeaninfo (Person.class ); propertydescriptor[] PropertyDescriptors = beaninfo.getpropertydescriptors ();//Get the property descriptor for ( PropertyDescriptor propertydescriptor:propertydescriptors) { System.out.println (Propertydescriptor.getname ( )); } }
Execution Result: Age class money name password xxx
Includes the attribute class inherited from the parent class.
Get all the properties in this class
@Test public void Test2 () throws Exception { //rejects the property inherited from Object BeanInfo BeanInfo = Introspector.getbeaninfo (Person.class, Object.class); propertydescriptor[] PropertyDescriptors = beaninfo.getpropertydescriptors (); For (PropertyDescriptor propertydescriptor:propertydescriptors) {System.out.println ( Propertydescriptor.getname ()); } }
Manipulating a bean's specified properties
@Test public void Test3 () throws Exception {person person = new Person (); PropertyDescriptor PropertyDescriptor = new PropertyDescriptor ("Age", Person.class); Get the Write method of the attribute, assign a value to the property method Setagemethod = Propertydescriptor.getwritemethod ();//Setage Setagemethod.invoke ( Person, a.); Gets the value of the property System.out.println (Person.getage ()); Method Getagemethod = Propertydescriptor.getreadmethod (); System.out.println (Getagemethod.invoke (person, null));}
Gets the type of the property of the current operation
@Test public void Test4 () throws Exception { PropertyDescriptor propertydescriptor = new PropertyDescriptor ("Money", Person.class); class<?> PropertyType = propertydescriptor.getpropertytype (); System.out.println (PropertyType); }
Java introspection mechanism Introspector