Pu Zhibing
2025-02-27 f0a9a41697a8568e8b3bd3436c450e68b3298916
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package com.panzhihua.common.utlis;
 
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
 
import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.reflectasm.MethodAccess;
 
import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
 
/**
 * 通用情况拷贝
 *
 * @author tkq
 * @date 14:36 2019/4/10
 */
@Slf4j
public class CopyUtil {
    private static final Logger logger = LoggerFactory.getLogger(CopyUtil.class);
 
    @SuppressWarnings("rawtypes")
    private static Map<Class, MethodAccess> methodMap = new ConcurrentHashMap<>();
 
    private static Map<String, Integer> methodIndexMap = new ConcurrentHashMap<>();
 
    @SuppressWarnings("rawtypes")
    private static Map<Class, List<String>> fieldMap = new ConcurrentHashMap<>();
 
    private CopyUtil() {
 
    }
 
    /**
     * <p>
     * 对数组进行拷贝
     * </p>
     *
     * @author tkq
     * @date 2018年12月19日
     */
    public static <T> List<T> copyList(List<?> desc, Class<T> targetClass) {
        if (desc == null) {
            return new ArrayList<>();
        }
        if (desc.isEmpty()) {
            return new ArrayList<>();
        }
        // 创建返回对象
        List<T> targetList = new ArrayList<>(desc.size());
        for (Object des : desc) {
            if (null != des) {
                try {
                    T newInstance = targetClass.newInstance();
                    copyProperties(des, newInstance);
                    targetList.add(newInstance);
                } catch (InstantiationException | IllegalAccessException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return targetList;
    }
 
    /**
     * <p>
     * 对数组进行拷贝
     * </p>
     *
     * @author manailin
     * @date 2018年12月19日
     */
    public static <T> List<T> beanCopyList(List<?> desc, Class<T> targetClass) {
        if (desc == null) {
            return new ArrayList<>();
        }
        if (desc.isEmpty()) {
            return new ArrayList<>();
        }
        // 创建返回对象
        List<T> targetList = new ArrayList<>(desc.size());
        for (Object des : desc) {
            if (null != des) {
                try {
                    T newInstance = targetClass.newInstance();
                    BeanUtil.copyProperties(des, newInstance);
                    targetList.add(newInstance);
                } catch (InstantiationException | IllegalAccessException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return targetList;
    }
 
    /**
     * @Title:
     * @Description: 根据目标对象类型进行拷贝
     * @author tkq
     * @date:2019/1/2
     * @Copyright: 2018 All rights reserved. 注意:禁止外泄以及用于其他的商业目
     */
    public static <T> T copyPropertiesByClass(Object desc, Class<T> targetClass) {
        if (desc != null) {
            try {
                T newInstance = targetClass.newInstance();
                copyProperties(desc, newInstance);
                return newInstance;
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        return null;
    }
 
    /**
     * 进行复制方法
     *
     * @param dataSource
     *            源目标对象
     * @param target
     *            目标对象
     * @author tkq
     * @date 14:37 2019-11-13
     */
    public static void copyProperties(Object dataSource, Object target) {
        if (target == null) {
            return;
        }
        if (dataSource == null) {
            return;
        }
        MethodAccess descMethodAccess = methodMap.get(target.getClass());
        if (descMethodAccess == null) {
            descMethodAccess = cache(target);
        }
        MethodAccess orgiMethodAccess = methodMap.get(dataSource.getClass());
        if (orgiMethodAccess == null) {
            orgiMethodAccess = cache(dataSource);
        }
 
        List<String> fieldList = fieldMap.get(dataSource.getClass());
        for (String field : fieldList) {
            String getKey = dataSource.getClass().getName() + "." + "get" + field;
            String setkey = target.getClass().getName() + "." + "set" + field;
            Integer setIndex = methodIndexMap.get(setkey);
            if (setIndex != null) {
                int getIndex = methodIndexMap.get(getKey);
                // 参数一需要反射的对象
                // 参数二class.getDeclaredMethods 对应方法的index
                // 参数对三象集合
                try {
                    descMethodAccess.invoke(target, setIndex.intValue(), orgiMethodAccess.invoke(dataSource, getIndex));
                } catch (Exception e) {
                    log.info("field:" + field);
                    throw e;
                }
            }
        }
    }
 
    /**
     * 单例模式
     *
     * @param object
     *            实体对象
     * @return MethodAccess
     * @author tkq
     * @date 14:36 2019/4/10
     */
    private static MethodAccess cache(Object object) {
        Class<?> name = object.getClass();
        synchronized (name) {
            MethodAccess methodAccess = MethodAccess.get(name);
            Class<?> className = object.getClass();
            Set<Field> fields = new HashSet<>();
            for (; className != Object.class; className = className.getSuperclass()) {
                fields.addAll(Arrays.asList(className.getDeclaredFields()));
            }
            List<String> fieldList = new ArrayList<>(fields.size());
            for (Field field : fields) {
                // 是否是私有的,是否是静态的
                if (Modifier.isPrivate(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) {
                    // 非公共私有变量
                    // 获取属性名称
                    String fieldName = StringUtils.capitalize(field.getName());
                    // 获取get方法的下标
                    int getIndex = methodAccess.getIndex("get" + fieldName);
                    // 获取set方法的下标
                    int setIndex = methodAccess.getIndex("set" + fieldName);
                    // 将类名get方法名,方法下标注册到map中
                    methodIndexMap.put(object.getClass().getName() + "." + "get" + fieldName, getIndex);
                    // 将类名set方法名,方法下标注册到map中
                    methodIndexMap.put(object.getClass().getName() + "." + "set" + fieldName, setIndex);
                    // 将属性名称放入集合里
                    fieldList.add(fieldName);
                }
            }
            // 将类名,属性名称注册到map中
            fieldMap.put(name, fieldList);
            methodMap.put(name, methodAccess);
            return methodAccess;
        }
    }
 
    /**
     * @description 复制属性
     * @param source
     *            源数据
     * @param targetClass
     *            目标对象类型
     * @return
     * @author weifei
     * @date 2020/8/20 10:38
     */
    public static <T, K> K copyProperties(T source, Class<K> targetClass) {
        if (source == null || targetClass == null) {
            return null;
        }
        // 创建对象
        try {
            K k = targetClass.newInstance();
            // 复制对象
            BeanUtils.copyProperties(source, k);
            return k;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
 
    /**
     * @description 复制属性
     * @param source
     *            源数据
     * @param targetClass
     *            目标对象类型
     * @return
     * @author weifei
     * @date 2020/12/16 10:12
     */
    public static <T, K> List<K> copyProperties(List<T> source, Class<K> targetClass) {
        if (source == null || targetClass == null) {
            return null;
        }
        List<K> returnValue = new ArrayList<>();
        try {
            source.forEach(s -> {
                K k = copyProperties(s, targetClass);
                if (k != null) {
                    returnValue.add(k);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return returnValue;
    }
 
    /**
     * @description 深度复制对象
     * @param source
     *            元数据
     * @param targetClass
     *            目标对象类型
     * @return
     * @author weifei
     * @date 2021/3/1 14:21
     */
    public static <T, K> K deepCopyObject(T source, Class<K> targetClass) {
        if (source == null || targetClass == null) {
            return null;
        }
        return JSONObject.parseObject(JSONObject.toJSONBytes(source), targetClass);
    }
 
    /**
     * @description 深度复制list对象
     * @param source
     *            元数据
     * @param targetClass
     *            目标对象类型
     * @return
     * @author weifei
     * @date 2021/3/1 14:26
     */
    public static <T, K> List<K> deepCopyListObject(List<T> source, Class<K> targetClass) {
        if (source == null || targetClass == null) {
            return null;
        }
        return JSONObject.parseArray(JSONObject.toJSONString(source), targetClass);
    }
}