• 一个自己用的复制对象的工具类


    代码中提供了两个方法,两个方法都需要填入 src 源对象 covertMap 映射集合,ignoreProperties 忽略复制字段
    其中一个方法需要传入一个Object对象,也就是目标对象,执行完copyProperties之后会把src中的值复制给target
    第二个需要传入目标对象的class,返回一个 传入类型的对对象
    convertMap的key是target也就是目标对象的属性名,value是src源对象的属性名

    package net.lesscoding.utils;
    
    import net.lesscoding.dto.First;
    import net.lesscoding.dto.Second;
    
    import java.beans.IntrospectionException;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.*;
    
    /**
     * @author eleven
     * @date 2022/9/9 10:01
     * @description
     */
    public class BeanUtil {
        public static void main(String[] args) {
            First first = new First();
            first.setName("first");
            first.setGender("女");
            Map<String,String> convertMap = new HashMap<>();
            convertMap.put("sex","gender");
            Second second = copyProperties(first, Second.class, convertMap,"name");
            System.out.println(second);
        }
    
        /**
         * 获取最终的映射集合,
         * @param source            源对象
         * @param target            目标对象
         * @param covertMap         不同字段的映射
         * @param ignoreProperties  忽略字段
         * @return Map              最终的转换字段
         */
        public static Map<String,String> targetMap(Object source, Object target, Map<String,String> covertMap,String... ignoreProperties){
            Map<String, String> sourceFieldMap = getDeclareProperties(source);
            Map<String, String> targetFieldMap = getDeclareProperties(target);
            targetFieldMap.putAll(sourceFieldMap);
            if(!isEmpty(covertMap)){
                targetFieldMap.putAll(covertMap);
                covertMap.forEach((k,v) -> {
                    targetFieldMap.remove(v);
                });
            }
            if(ignoreProperties != null && ignoreProperties.length > 0){
                for (String ignoreProperty : ignoreProperties) {
                    targetFieldMap.remove(ignoreProperty);
                }
            }
            if(isEmpty(targetFieldMap)){
                throw new IllegalArgumentException("The target filed map is empty,please check the ignoreProperties");
            }
            return targetFieldMap;
        }
    
    
        /**
         * 复制两个对象
         * @param source                源对象
         * @param target                目标对象
         * @param covertMap             不同字段的映射,相同的字段不需要传入,只需要传入不同的字段
         * @param ignoreProperties      复制忽略字段
         * @return  Object              返回复制好的苗木表对象
         */
        public static Object copyProperties(Object source, Object target, Map<String,String> covertMap,String... ignoreProperties){
            if(source == null){
                throw new IllegalArgumentException("Source objects are not allowed to be empty");
            }
            if(target == null){
                throw new IllegalArgumentException("Target objects must be not null");
            }
            Map<String, String> targetFieldMap = targetMap(source, target, covertMap, ignoreProperties);
            copy(targetFieldMap,source,target);
            return target;
        }
    
        /**
         * 根据字段映射复制字段
         * @param targetMap     最终的字段映射
         * @param source        源对象
         * @param target        目标对象
         */
        public static void copy(Map<String, String> targetMap,Object source,Object target){
            PropertyDescriptor sourceProperty = null;
            PropertyDescriptor targetProperty = null;
            Method sourceGet = null;
            Method targetSet = null;
            for (String key : targetMap.keySet()) {
                String value = targetMap.get(key);
                try {
                    sourceProperty = new PropertyDescriptor(value,source.getClass());
                    targetProperty = new PropertyDescriptor(key,target.getClass());
                    sourceGet = sourceProperty.getReadMethod();
                    targetSet = targetProperty.getWriteMethod();
                    Object sourceField = sourceGet.invoke(source);
                    targetSet.invoke(target,sourceField);
                } catch (IntrospectionException e) {
    
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
    
            }
        }
    
        /**
         * 赋值对象
         * @param src                       源对象
         * @param targetClass               目标对象的Class对象
         * @param convertMap                两个对象中差异的字段映射, 只需要传入不同的
         * @param ignoreProperties          做复制时要忽略的字段
         * @param                        目标对象的泛型,自动获取
         * @return T                        返回目标对象
         */
        public static <T> T copyProperties(Object src, Class<T> targetClass, Map<String, String> convertMap, String... ignoreProperties){
            Object target = null;
            if(targetClass == null){
                throw new IllegalArgumentException("Target class must be not null");
            }
            try {
                target = copyProperties(src, targetClass.newInstance(), convertMap, ignoreProperties);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return targetClass.cast(target);
        }
    
        /**
         * 获取传入对象的输赢
         * @param obj       源对象
         * @return Map      将属性做成一个映射
         */
        public static Map<String, String> getDeclareProperties(Object obj){
            Class<?> aClass = obj.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            Map<String,String> resultMap = new HashMap<>(declaredFields.length);
            Arrays.asList(declaredFields).stream()
                    .forEach(item -> resultMap.put(item.getName(),item.getName()));
            return resultMap;
        }
    
        /**
         * 判断map是否为空
         * @param   map         传入的map
         * @return  Boolean
         */
        public static Boolean isEmpty(Map map){
            return map == null || map.size() == 0;
        }
    }
    
    • 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
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
  • 相关阅读:
    web应用及微信小程序版本更新检测方案实践
    一个实用的链接导航页的站点设计 支持自定义链接
    Python通过下标获取指定的文件并复制到一个新的文件
    ros1 实现Server端自定义四 Topic模式控制海龟运动
    全网独家首发!一份破解大厂面试官千层套路的Spring源码笔记
    DOM——文件对象模型(元素位置、盒子模型)
    Linux操作系统之进程
    可编程交易区块为DeFi机器人提供强大动力
    【蒸汽冷凝器型号和PI控制】具有PID控制的蒸汽冷凝器的动力学模型(Matlab&Simulink)
    【K8S系列】第七讲:有状态服务 VS 无状态服务
  • 原文地址:https://blog.csdn.net/qq_42059717/article/details/126780802