我正在尝试将一个对象的属性值复制到另一个对象。下面提到的示例运行良好。但是,当尝试使用子级属性copy时,它不会忽略空值。我也想忽略父级和子级中的空值。
如何在将对象从一个对象复制到另一个对象时忽略子级别的空值?
我使用的是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;      
     }
  }
}发布于 2019-12-21 01:43:54
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);
}https://stackoverflow.com/questions/59278418
复制相似问题