How to ignore null values using springframework BeanUtils copyProperties?

后端 未结 6 1327
悲哀的现实
悲哀的现实 2020-12-01 00:09

I would like to know how to copy the properties from an Object Source to an Object Dest ignoring null values​​ using Spring Framework.

I actually use Apache beanutil

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 01:01

    A better solution based on Pawel Kaczorowski's answer:

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
        return Stream.of(wrappedSource.getPropertyDescriptors())
            .map(FeatureDescriptor::getName)
            .filter(propertyName -> {
                try {
                   return wrappedSource.getPropertyValue(propertyName) == null
                } catch (Exception e) {
                   return false
                }                
            })
            .toArray(String[]::new);
    }
    

    For example, if we have a DTO:

    class FooDTO {
        private String a;
        public String getA() { ... };
        public String getB();
    }
    

    Other answers will throw exceptions on this special case.

提交回复
热议问题