copyProperties复制两个对象的属性
前不久, 在开发的过程中, 遇到了两个相同类的对象复制属性, 一时没有想到好的办法, 那么今天就来学习一下, 同时留下笔记为日后需要做准备, 话不多说,直接上code
实体类实例:
/**
* @author xinruoxiangyang9010
*/
@Data
public class CustomerOne {
private String customerName;
private Integer age;
private String telNumber;
}
使用org.springframework.beans.BeanUtils进行测试:
import org.springframework.beans.BeanUtils;
import util.entity.CustomerOne;
/**
* @author xinruoxiangyang9010
* 将实体类customer1的属性复制到customer2上
*/
public class BeanValueCopy {
public static void main(String[] args) {
CustomerOne source = new CustomerOne();
source.setCustomerName("张三");
CustomerOne target = new CustomerOne();
copyValue1(source, target);
System.out.println(target);
// 结果: CustomerOne(customerName=张三, age=null, telNumber=null)
}
public static void copyValue1(CustomerOne source, CustomerOne target) {
BeanUtils.copyProperties(source, target);
}
}
注意事项:
- 以上示例是在target属性值都为null时的测试
- 如果target某个属性原本有值, source对应属性也有值, 则结果为source覆盖target
- 如果target某个属性原本有值, source对应属性为null, 则结果为null
- 该复制方法为浅拷贝
复制时忽略部分属性
/**
* 忽略单一属性age
*/
public static void copyValue2(CustomerOne source, CustomerOne target) {
BeanUtils.copyProperties(source, target, "age");
}
忽略多个属性
public static void copyValue3(CustomerOne source, CustomerOne target) {
String[] ignoreProperties = {"age", "telNumber"};
BeanUtils.copyProperties(source, target, ignoreProperties);
}
开发中会遇到另外一种需求, 不想source中值为null的属性覆盖到target中, 借助hutool:
<!-- 依赖只做参考 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.8.20</version>
</dependency>
这里注意导包
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import util.entity.CustomerOne;
/**
* @author xinruoxiangyang9010
* 复制忽略Null值
*/
public class BeanValueCopy2 {
public static void main(String[] args) {
CustomerOne source = new CustomerOne();
source.setCustomerName("张三");
source.setTelNumber("1350000");
CustomerOne target = new CustomerOne();
target.setAge(28);
copyValue1(source, target);
System.out.println(target);
// 结果: CustomerOne(customerName=张三, age=28, telNumber=null)
}
public static void copyValue1(CustomerOne source, CustomerOne target) {
CopyOptions copyOptions = CopyOptions.create()
// source中的null不会进行复制
.setIgnoreNullValue(true)
// 忽略转换错误
.setIgnoreError(true)
// 设置不想复制的属性, 支持多个
.setIgnoreProperties("telNumber");
BeanUtil.copyProperties(source, target, copyOptions);
}
}
注意:
- copyProperties方法的入参为Object类型, 也就是当不同类型对象之间也可实现属性复制
- 不同类型对象在进行复制操作时要满足属性名相同, 且属性的类型也相同(切记)
文章介绍了在Java开发中如何使用Spring的BeanUtils工具类以及Hutool库进行对象属性的复制,包括浅拷贝、忽略特定属性和不复制null值的情况。示例代码展示了从一个对象复制属性到另一个对象的过程,并提到了不同复制策略的注意事项。
5521

被折叠的 条评论
为什么被折叠?



