BeanUtils.opyproperties()忽略null,再封装实现

利用Java反射机制基于 org.springframework.beans.BeanUtils的再封装!上代码!

public class BeanCopyUtil {
    public static String[] getNullPropertyNames (Object source) throws IllegalAccessException {
        List<String> res = new ArrayList<>();
        Class<?> aClass = source.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field: declaredFields) {
                field.setAccessible(true);
                Object value = field.get(source);
                if(value == null){
                    res.add(field.getName());
                }
        }
        return res.toArray(new String[0]);
    }
    public static void copyPropertyIgnoreNullVal(Object source,Object target) throws IllegalAccessException {
        BeanUtils.copyProperties(source,target,getNullPropertyNames(source));
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BeanUtils.copyProperties方法可以用于对象之间的属性拷贝,但默认情况下它会将源对象的所有属性值拷贝到目标对象中,包括null值。如果需要忽略源对象中的null值属性,可以使用BeanUtils.copyProperties方法的第三个参数,即属性过滤器。 属性过滤器是一个实现了org.springframework.be.BeanUtils.CopyablePropertyFilter接口的对象,它可以控制哪些属性需要被拷贝。在属性过滤器的accept方法中,可以根据属性值是否为null来决定是否拷贝该属性。 以下是一个示例代码,演示了如何使用BeanUtils.copyProperties方法忽略null值: ```java import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.CopyablePropertyFilter; public class CopyPropertiesExample { public static void main(String[] args) { SourceObject source = new SourceObject(); source.setName("John"); source.setAge(25); source.setAddress(null); TargetObject target = new TargetObject(); BeanUtils.copyProperties(source, target, (sourceValue, targetValue, targetPropertyDescriptor) -> { // 忽略源对象中的null值属性 return sourceValue != null; }); System.out.println(target.getName()); // 输出:John System.out.println(target.getAge()); // 输出:25 System.out.println(target.getAddress()); // 输出:null } } class SourceObject { private String name; private int age; private String address; // 省略getter和setter方法 } class TargetObject { private String name; private int age; private String address; // 省略getter和setter方法 } ``` 在上述示例中,我们创建了一个SourceObject对象,并设置了name、age和address属性,其中address属性的值为null。然后我们创建了一个TargetObject对象,并使用BeanUtils.copyProperties方法将SourceObject的属性拷贝到TargetObject中,通过属性过滤器忽略了源对象中的null值属性。最后我们输出了TargetObject对象的属性值,可以看到address属性的值为null

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值