What is a JavaBean?
A special class used to pass data information, whose methods are used to access private fields, and whose methods conform to some naming convention.
The characteristics of the JavaBean
- Properties are private
- There are no-parameter constructors
- The getter/setter methods for private properties are getXxx/setXxx
- Getter methods must have a return value and no input parameters, and setter methods must have an input parameter and no return value
Classes that conform to these characteristics are called Javabeans.
The JDK provides a set of apis for accessing getter/setter methods for a property, which is Java introspection.
Introspection and reflection
Reflection: The JVM can access the properties and methods of this class at runtime for any object.
Introspector: The Processing method of JavaBean attributes and events in The Java language
- Reflection is for any class, any object, and introspection is only for Javabeans. Introspection manipulates JavaBean properties through reflection.
- Introspection setting property values definitely calls setter methods, reflection does not necessarily (Field object)
- Reflection is like a mirror, seeing everything about an object, an objective fact. Introspection is more subjective, like looking at getClass() and thinking that there is a class field in this class, which is not necessarily the case.
example
public class Main { public static void main(String[] args) throws Exception{ BeanInfo beanInfo = Introspector.getBeanInfo(People.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { System.out.print(propertyDescriptor.getName()+" "); }} // program output: age class name // We know that every object has a getClass method, so when we use introspection, } class People{String name; int age; 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; }}Copy the code
Propertydescriptors: property descriptors that describe properties in Javabeans, by which we can know the type of the property and get methods to manipulate the property (getters/setters)