BeanUtil.copyProperties的优化与使用(解决copyProperties null值覆盖问题)


前言

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));

总结

欢迎讨论。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值