BeanDesc

Introduction

Hutool encapsulates the information description of Beans by parsing all the relevant information of a Bean through reflection. This class is similar to the JDK’s BeanInfo and can also be understood as a enhanced version of this class.

BeanDesc includes all fields (properties) and their corresponding getter and setter methods. Unlike BeanInfo, BeanDesc requires strict correspondence between attributes and getter/setter methods, i.e., if there is a non-public attribute without a getter, the attribute value cannot be obtained, and without a setter, attribute values cannot be injected.

The mapping rules for attributes and getter/setter methods are as follows:

  1. Ignore the case sensitivity of field and method names during matching.
  2. If the field name is XXX, the getter searches for getXXX, isXXX, getIsXXX.
  3. If the field name is XXX, the setter searches for setXXX, setIsXXX.
  4. The setter ignores parameter values that do not match the field value, so when there are multiple overloaded parameters, the first matching one will be invoked.

Usage

We define a more complex Bean:

public static class User {
	private String name;
	private int age;
	private boolean isAdmin;
	private boolean isSuper;
	private boolean gender;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public User setAge(int age) {
		this.age = age;
		return this;
	}
	public String testMethod() {
		return "test for " + this.name;
	}
	public boolean isAdmin() {
		return isAdmin;
	}
	public void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}
	public boolean isIsSuper() {
		return isSuper;
	}
	public void setIsSuper(boolean isSuper) {
		this.isSuper = isSuper;
	}
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + ", isAdmin=" + isAdmin + ", gender=" + gender + "]";
	}
}

Field getter method acquisition

  1. General fields
BeanDesc desc = BeanUtil.getBeanDesc(User.class);
// User
desc.getSimpleName();

// age
desc.getField("age").getName();
// getAge
desc.getGetter("age").getName();
// setAge
desc.getSetter("age").getName();
  1. Boolean fields

we observe the User class, the boolean field is named isAdmin, and in this case, the getter with the same name can also be obtained:

BeanDesc desc = BeanUtil.getBeanDesc(User.class);

// isAdmin
desc.getGetter("isAdmin").getName()

Of course, if the user believes that isIsXXX is correct, BeanDesc can also perfectly obtain it, taking isSuper as an example:

// isIsSuper
desc.getGetter("isSuper");

Field property assignment

BeanDesc desc = BeanUtil.getBeanDesc(User.class);
User user = new User();
desc.getProp("name").setValue(user, "张三");