【问题标题】:Spring Bean copy properties ignore child's object null valuesSpring Bean 复制属性忽略子对象的空值
【发布时间】:2020-04-04 07:12:20
【问题描述】:

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

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

我正在使用 Spring Bean 工具。如果 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;      
     }
  }
}

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 2017-11-11
      • 2016-10-13
      • 2013-12-28
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多