对象属性拷贝效率优化

参考你还在用BeanUtils进行对象属性拷贝?

import org.springframework.cglib.beans.BeanCopier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 封装属性拷贝工具类
 */
public class BeanCopierUtil {
    private static final Map BEAN_COPIER_CACHE_MAP = new ConcurrentHashMap<>();

    public static void copy(Object source, Object target) {
        BeanCopier copier = getBeanCopier(source.getClass(), target.getClass());
        copier.copy(source, target, null);
    }

    private static BeanCopier getBeanCopier(Class sourceClass, Class targetClass) {
        String cacheKey = generateKey(sourceClass, targetClass);
        BeanCopier copier;
        if (!BEAN_COPIER_CACHE_MAP.containsKey(cacheKey)) {
            copier = BeanCopier.create(sourceClass, targetClass, false);
            BEAN_COPIER_CACHE_MAP.put(cacheKey, copier);
        } else {
            copier = BEAN_COPIER_CACHE_MAP.get(cacheKey);
        }
        return copier;
    }

    private static String generateKey(Class class1, Class class2) {
        return class1.toString() +"_"+ class2.toString();
    }

}

你可能感兴趣的:(对象属性拷贝效率优化)