BeanUtils.copyProperties在拷贝属性时忽略空值

BeanUtils.copyProperties在拷贝属性时忽略空值

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * BeanUtils.copyProperties 复制忽略null值
 */
@Component
public class CopyUtil {
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        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 (String[]) emptyNames.toArray(result);
    }

    public static void copyProperties(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BeanUtils.copyProperties方法是Apache Commons BeanUtils库中的一个工具方法,用于将一个Java对象的属性值复制到另一个Java对象中。默认情况下,该方法会将源对象的所有属性值复制到目标对象中,包括空值属性。 如果你想要排除空值属性,可以使用自定义的属性拷贝器(PropertyUtilsBean)来实现。以下是一种可能的实现方式: 1. 创建一个自定义的属性拷贝器类,继承自PropertyUtilsBean类,并重写copyProperties方法。 ```java import org.apache.commons.beanutils.PropertyUtilsBean; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.DynaBean; public class CustomPropertyUtils extends PropertyUtilsBean { @Override public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor origDescriptor : origDescriptors) { String name = origDescriptor.getName(); if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) { Object value = PropertyUtils.getSimpleProperty(orig, name); if (value != null) { PropertyUtils.setSimpleProperty(dest, name, value); } } } } } ``` 2. 在你的代码中使用自定义的属性拷贝器类进行属性拷贝。 ```java CustomPropertyUtils customPropertyUtils = new CustomPropertyUtils(); customPropertyUtils.copyProperties(destObject, sourceObject); ``` 这样,只有源对象中非属性值才会被复制到目标对象中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值