前言
BeanUtil.copyProperties的优化与使用
一、copyProperties是什么?
在java中,我们想要将一个类的值赋值给另一个类,那么就需要使用到copyProperties函数,例如BeanUtil.copyProperties(Object source, Object target)。
二、使用步骤
1.引入库
引入如下对应工具类:
//这里引入的是5.3.1版本hutool工具类
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.1</version>
</dependency>
//在代码中注入地址
import cn.hutool.core.bean.BeanUtil;
2.基础使用
将A中一样的字段值复制给B:
Student studentA = new Student();
Student studentB = new Student();
//将A的值赋值给B
BeanUtil.copyProperties(studentA,studentB);
3.进阶使用
我们点入hutool源码,可以看到支持第三个参数填写:
/**
* 复制Bean对象属性<br>
* 限制类用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类
*
* @param source 源Bean对象
* @param target 目标Bean对象
* @param ignoreProperties 不拷贝的的属性列表
*/
public static void copyProperties(Object source, Object target, String... ignoreProperties) {
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
}
因此可以看出,我们可以自定义不copy的字段名,例如:我不想把A中的name值赋值给B 可以按照如下写:
Student studentA = new Student();
Student studentB = new Student();
String[] strArray = new String[1];
strArray[0] = "name";
//将A的值赋值给B
BeanUtil.copyProperties(studentA,studentB,strArray);
4.实用场景
在业务中,比较实用的是不将对象中的null值进行覆盖,可以使用以下支持函数
/**
* 解决BeanUtils.copyProperties() 的 null值覆盖问题(基本类型的0 0.0)
* @param source
* @return
*/
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null || Objects.equals(srcValue,0) || Objects.equals(srcValue,0.0)) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
Student studentA = new Student();
Student studentB = new Student();
//studentA中的null值不进行赋值
BeanUtil.copyProperties(studentA,studentB,getNullPropertyNames(studentA));
总结
欢迎讨论。