一、介绍:
BeanUtils 是 Spring 框架提供的一个工具类,用于操作 JavaBeans。它提供了一系列的方法来简化 JavaBeans 的操作,尤其是在复制对象属性时非常有用(日常crud开发少不了的工具)。以下是 BeanUtils 中一些常用的方法。
二、常用方法总结:
1、copyProperties()
这个方法用的频率很高,主要用于将一个 JavaBean 的属性值复制到另一个 JavaBean 中。如果两个 JavaBean 有相同的属性名,则可以轻松地复制属性值。在dto pojo vo等等之间的转换非常有用。
// 在拷贝属性的同时,可以忽略某些属性。
copyProperties(Object source,
Object target, String... ignoreProperties):
import org.springframework.beans.BeanUtils;
public class Person {
private String name;
private int age;
// getters and setters
}
public class Employee extends Person {
private String department;
// getters and setters
}
public static void main(String[] args) {
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
Employee employee = new Employee();
BeanUtils.copyProperties(person, employee);
System.out.println(employee.getName()); // 输出 "John Doe"
System.out.println(employee.getAge()); // 输出 30
}
2、populate()
使用 Map 中的键值对填充 JavaBean 的属性。
Map<String, Object> map = new HashMap<>();
map.put("name", "Jane Smith");
map.put("age", 28);
Person person = new Person();
BeanUtils.populate(person, map);
System.out.println(person.getName()); // 输出 "Jane Smith"
System.out.println(person.getAge()); // 输出 28
3、describe()
返回一个包含 JavaBean 属性名称及其值的 Map。
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
Map<String, Object> properties = BeanUtils.describe(person);
for (String key : properties.keySet()) {
System.out.println(key + ": " + properties.get(key));
}
4、getProperty(Object bean, String name):
获取指定Bean的指定属性值。
import org.springframework.beans.BeanUtils;
public class BeanUtilsExample {
public static void main(String[] args) {
// 创建一个 Person 对象并设置属性值
Person person = new Person();
person.setName("Alice");
person.setAge(30);
// 使用 getProperty 方法获取属性值
String name = BeanUtils.getProperty(person, "name");
String age = BeanUtils.getProperty(person, "age");
// 输出结果
System.out.println("Name: " + name); // 输出 "Name: Alice"
System.out.println("Age: " + age); // 输出 "Age: 30"
}
}
5、setProperty(Object bean, String name, Object value):
设置指定Bean的指定属性值。
import org.springframework.beans.BeanUtils;
public class BeanUtilsExample {
public static void main(String[] args) {
// 创建一个 Person 对象
Person person = new Person();
// 使用 setProperty 方法设置属性值
BeanUtils.setProperty(person, "name", "Alice");
BeanUtils.setProperty(person, "age", 30);
// 输出结果
System.out.println("Name: " + person.getName()); // 输出 "Name: Alice"
System.out.println("Age: " + person.getAge()); // 输出 "Age: 30"
}
}