- 0
- 0
BeanUtils字段复制工具如何忽略null值字段
原创BeanUtils字段复制工具如何忽略null值字段
Java

亮月官方
2020-10-13 10:59:27
阅读数:417
BeanUtilsBeanUtils Copy复制忽略"null"
方案一
在做项目时遇到需要copy两个对象之间的属性值,但是有源对象有null值,在使用BeanUtils来copy时null值会覆盖目标对象的同名字段属性值,然后采用以下方法找到null值字段,然后忽略
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
public static void copyPropertiesIgnoreNull(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
方案二
hutool开源库Bean工具-BeanUtil,
- 引入依赖包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.4</version>
</dependency>
- 代码使用
UserDetail userDetail=new UserDetail();
UserDetail newDetail=new UserDetail();
BeanUtil.copyProperties(userDetail,newDetail);
一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情,文章最后更新于:2020-10-13 10:59:27
Java对多个word文档合并支持图片、图表、图形、表格等
超简单最新版本Eclipse安装入门使用教程(2020最新版)
loading