fuliqi
2024-11-29 4ee9e6833f738e22390c4e875fe140c2b96cfcc2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.ycl.common.utils;
 
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
 
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
 
/**
 * 自定义复制工具类
 */
public class CopyUtils {
        /**
         * 所有为空值的属性都不copy
         *
         * @param source
         * @param target
         */
        public static void copyNoNullProperties(Object source, Object target) {
            BeanUtils.copyProperties(source, target, getNullField(source));
        }
 
        /**
         * 获取属性中为空的字段
         *
         * @param target
         * @return
         */
        private static String[] getNullField(Object target) {
            BeanWrapper beanWrapper = new BeanWrapperImpl(target);
            PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
            Set<String> notNullFieldSet = new HashSet<>();
            if (propertyDescriptors.length > 0) {
                for (PropertyDescriptor p : propertyDescriptors) {
                    String name = p.getName();
                    Object value = beanWrapper.getPropertyValue(name);
                    if (Objects.isNull(value)) {
                        notNullFieldSet.add(name);
                    }
                }
            }
            String[] notNullField = new String[notNullFieldSet.size()];
            return notNullFieldSet.toArray(notNullField);
        }
}