Outline:
- JavaBean specification
- introspection
A, JavaBean specifications
JavaBean - like subject to the following specifications.
- Implement java.io.Serializable.
- javaBean property is a private member variables have getter / setter methods. It can also be provided only getter methods, such as read-only attribute called attribute; can also be provided only setter methods, such property called write-only property.
- JavaBean must have an empty constructor
- JavaBean must have a public constructor
Second, introspection
- First introspective nature is reflective use
- You can quickly get getter and setter javaBean variable by introspection, to quickly operate bean object.
Test javaBean
public class Person { private String name ; private int age ; public void say(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
1. JavaBean class descriptor can get all the properties and methods of an object by BeanInfo
public static void main (String [] args) throws Exception { // Get BeanInfo object that is used to acquire an attribute description javaBean BeanInfo BeanInfo = Introspector.getBeanInfo (the Person. class ); // The method described is MethodDescriptor [] methodDescriptors = beanInfo.getMethodDescriptors (); // attribute descriptor the PropertyDescriptor [] = propertyDescriptors beanInfo.getPropertyDescriptors (); // test object the Person Person = new new the Person (); for (the PropertyDescriptor PropertyDescriptor: propertyDescriptors) { //属性名 System.out.println("Person的属性:"+propertyDescriptor.getName()); if("name".equals(propertyDescriptor.getName())){ //属性读方法 Method readMethod = propertyDescriptor.getReadMethod(); //属性的写方法 Method writeMethod = propertyDescriptor.getWriteMethod(); writeMethod.invoke(person,"xiaoming"); System.out.println("person的name:"+readMethod.invoke(person)); Class<?> propertyType = propertyDescriptor.getPropertyType(); System.out.println ("Type property:" + propertyType.getName ()); } } }
2. direct access to a property descriptor
public static void main (String [] args) throws Exception { the Person p = new new the Person (); // direct access by name descriptor attribute // Get the name attribute descriptor facilitate our direct manipulation of the object name property p. Descriptor = the PropertyDescriptor new new the PropertyDescriptor (. "Name", the Person class ); Method, writeMethod = descriptor.getWriteMethod (); writeMethod.invoke (P, "nananan" ); System.out.println ( "Person Object name:" + descriptor. . getReadMethod () Invoke (P)); }