返回

BeanUtils.copyProperties 的使用及注意点

后端

BeanUtils.copyProperties 的使用

BeanUtils.copyProperties 的基本用法非常简单,只需要两个参数:

  • 源对象:要复制属性的对象
  • 目标对象:要接收属性的对象
// 创建源对象
Person source = new Person();
source.setName("张三");
source.setAge(20);

// 创建目标对象
Student target = new Student();

// 使用 BeanUtils.copyProperties 复制属性
BeanUtils.copyProperties(source, target);

// 输出目标对象属性值
System.out.println(target.getName()); // 张三
System.out.println(target.getAge()); // 20

需要注意的是,BeanUtils.copyProperties 只会复制源对象和目标对象中具有相同名称和类型的属性。如果源对象中某个属性在目标对象中不存在,或者类型不匹配,则该属性不会被复制。

BeanUtils.copyProperties 的技巧和注意事项

1. 使用 ignoreProperties 忽略某些属性

在某些情况下,我们可能需要忽略源对象中的某些属性,不复制到目标对象中。可以使用 ignoreProperties 参数来指定要忽略的属性。

// 创建源对象
Person source = new Person();
source.setName("张三");
source.setAge(20);
source.setSex("男");

// 创建目标对象
Student target = new Student();

// 使用 BeanUtils.copyProperties 复制属性,忽略 sex 属性
BeanUtils.copyProperties(source, target, "sex");

// 输出目标对象属性值
System.out.println(target.getName()); // 张三
System.out.println(target.getAge()); // 20
System.out.println(target.getSex()); // null

2. 使用 copyPropertiesIgnoreNull 来忽略 null 值

默认情况下,BeanUtils.copyProperties 会将源对象中所有非 null 值的属性复制到目标对象中。如果我们只想复制非 null 值的属性,可以使用 copyPropertiesIgnoreNull 方法。

// 创建源对象
Person source = new Person();
source.setName("张三");
source.setAge(null);
source.setSex("男");

// 创建目标对象
Student target = new Student();

// 使用 BeanUtils.copyPropertiesIgnoreNull 复制属性,忽略 null 值
BeanUtils.copyPropertiesIgnoreNull(source, target);

// 输出目标对象属性值
System.out.println(target.getName()); // 张三
System.out.println(target.getAge()); // null
System.out.println(target.getSex()); // 男

3. 使用 PropertyUtils 来设置和获取属性值

在某些情况下,我们可能需要直接设置或获取对象的属性值,而不需要使用 BeanUtils.copyProperties。可以使用 PropertyUtils 来实现这个目的。

// 创建对象
Person person = new Person();

// 使用 PropertyUtils 设置属性值
PropertyUtils.setProperty(person, "name", "张三");
PropertyUtils.setProperty(person, "age", 20);

// 使用 PropertyUtils 获取属性值
String name = (String) PropertyUtils.getProperty(person, "name");
int age = (int) PropertyUtils.getProperty(person, "age");

// 输出属性值
System.out.println(name); // 张三
System.out.println(age); // 20

总结

BeanUtils.copyProperties 是 Java 中一个非常有用的工具类,它可以方便地将一个对象的属性值复制到另一个对象中。在本文中,我们介绍了 BeanUtils.copyProperties 的基本用法,以及一些使用技巧和注意事项。希望这些内容能够对您有所帮助。