Spring Bean复制属性忽略子对象的null值

时间:2019-12-11 03:16:07

标签: java spring spring-bean apache-commons-beanutils

我正在尝试将一个对象的属性值复制到另一个对象。下面提到的示例效果很好。但是,在尝试使用子级属性复制时,它并不会忽略空值。我也想忽略父级和子级中的空值。

在将对象从一个对象复制到另一个对象时,如何忽略子级别的空值?

我正在使用Spring Bean utils。如果Apache utils中提供的解决方案也可以。

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

// then use Spring BeanUtils to copy and ignore null using our function
public static void myCopyProperties(Object src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}


 class Person {
  private String name;
  private Address address;

  public static class Address {
     private String apt;
     private String state;
     private ContactInfo contactInfo;

     public static class ContactInfo {
        private String primaryEmail;
        private String secEmail;      
     }
  }
}

1 个答案:

答案 0 :(得分:0)

com.demo.test是我的项目包。如果有任何对象属于我的包,我将进行回归以复制值。可以。

public static String[] getNullPropertyNames (Object source, Object target) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    final BeanWrapper targetBean = new BeanWrapperImpl(target);
    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());
        }else  {
            Class<?> accessor = src.getPropertyType(pd.getName());
            String cname = accessor.getCanonicalName();
            if(cname.contains("com.demo.test")) {
                Object targetVal = targetBean.getPropertyValue(pd.getName());
               if(targetVal  != null) {
                BeanUtils.copyProperties(srcValue,targetVal , getNullPropertyNames(srcValue,targetVal));
                emptyNames.add(pd.getName());
                  }
            }
        }
    }

    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}