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
| package org.sang.utils;
import lombok.extern.slf4j.Slf4j; import org.springframework.cglib.beans.BeanCopier;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j public class CGlibCopier {
private static final ConcurrentHashMap<String, BeanCopier> mapCaches = new ConcurrentHashMap<>();
public static <O, T> T copy(O source, Class<T> target) { T instance = baseCopy(source, target); return instance; }
public static <O, T> T copy(O source, Class<T> target, IAction<T> action) { T instance = baseCopy(source, target); action.run(instance); return instance; }
public static <O, T> T copyObject(O source, T target) { String baseKey = generateKey(source.getClass(), target.getClass()); BeanCopier copier; if (!mapCaches.containsKey(baseKey)) { copier = BeanCopier.create(source.getClass(), target.getClass(), false); mapCaches.put(baseKey, copier); } else { copier = mapCaches.get(baseKey); } copier.copy(source, target, null); return target; }
public static <O, T> T copyObject(O source, T target, IAction<T> action) { String baseKey = generateKey(source.getClass(), target.getClass()); BeanCopier copier; if (!mapCaches.containsKey(baseKey)) { copier = BeanCopier.create(source.getClass(), target.getClass(), false); mapCaches.put(baseKey, copier); } else { copier = mapCaches.get(baseKey); } copier.copy(source, target, null); action.run(target); return target; }
private static <O, T> T baseCopy(O source, Class<T> target) { String baseKey = generateKey(source.getClass(), target); BeanCopier copier; if (!mapCaches.containsKey(baseKey)) { copier = BeanCopier.create(source.getClass(), target, false); mapCaches.put(baseKey, copier); } else { copier = mapCaches.get(baseKey); } T instance = null; try { instance = target.getDeclaredConstructor().newInstance(); } catch (Exception e) { log.error("baseCopy 创建对象异常" + e.getMessage()); } copier.copy(source, instance, null); return instance; }
private static String generateKey(Class<?> class1, Class<?> class2) { return class1.toString() + class2.toString(); } } @FunctionalInterface interface IAction<T>{ void run(T target); }
|