BeanUtil复制对象非空属性

本文深入探讨了BeanUtil工具类在对象属性复制时如何避免空值覆盖的问题,提供了实用的代码示例,包括如何仅复制非空属性值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发中经常用到对象的copy,而BeanUtil工具类是大多数人copy对象的选择.很多时候,我们在copy时,需要排除掉源对象 属性为空的值,以免其覆盖目标对象的值,这时候就需要把源对象中属性为空的值找出来,工具类如下.

1.BeanUtil直接copy,可以把User对象的属性值都copy给User1,但是这样就把User1的nickName给覆盖为null了

    public static void main(String[] args) {

        User user = new User();
        user.setName("李白");
        user.setScore(80);
        User user1 = new User();
        user1.setNickName("啦啦");
        BeanUtil.copyProperties(user,user1);

    }

2.BeauUtil只copy源对象中属性非空的值

    public static void main(String[] args) {
       User user = new User();
       user.setName("李白");
       user.setScore(80);
       User user1 = new User();
       user1.setNickName("啦啦");
       BeanUtil.copyProperties(user,user1,IgnorePropertiesUtil.getNullPropertyNames(user));
    }

工具类:

public class IgnorePropertiesUtil {
    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        return emptyNames.toArray(new String[emptyNames.size()]);
    }
}

BeanUtil源码:

	/**
	 * Copy the property values of the given source bean into the given target bean,
	 * ignoring the given "ignoreProperties".
	 * <p>Note: The source and target classes do not have to match or even be derived
	 * from each other, as long as the properties match. Any bean properties that the
	 * source bean exposes but the target bean does not will silently be ignored.
	 * <p>This is just a convenience method. For more complex transfer needs,
	 * consider using a full BeanWrapper.
	 * @param source the source bean
	 * @param target the target bean
	 * @param ignoreProperties array of property names to ignore
	 * @throws BeansException if the copying failed
	 * @see BeanWrapper
	 */
	public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
		copyProperties(source, target, null, ignoreProperties);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值