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

  1. Properties are private
  2. There are no-parameter constructors
  3. The getter/setter methods for private properties are getXxx/setXxx
  4. 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

  1. Reflection is for any class, any object, and introspection is only for Javabeans. Introspection manipulates JavaBean properties through reflection.
  2. Introspection setting property values definitely calls setter methods, reflection does not necessarily (Field object)
  3. 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)