对象拷贝

import org.springframework.cglib.beans.BeanCopier;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;/** * @ClassName: BeanCopyUtils * @...

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

/**
* @ClassName: BeanCopyUtils
* @author: yaozhenhua
* @date: 2019/1/29 16:47
*/
public class BeanCopyUtils {
private static ConcurrentHashMap<String, BeanCopier> beanCopierConcurrentHashMap = new ConcurrentHashMap<>();

public static <T> T copyEntity(Object source, Class<T> destClazz) throws IllegalAccessException, InstantiationException {
if(source==null){
return null;
}
return copyBean(getCopier(source, destClazz), source, destClazz);
}

public static <T> T copyObject(Object source, T t) {
return copyBean(getCopier(source, t), source, t);
}

public static <T> List<T> copyList(List<?> source, Class<T> destClazz) throws IllegalAccessException, InstantiationException {
if (!EmptyUtils.isEmpty(source)) {
Object tempItem = source.get(0);
BeanCopier beanCopier = getCopier(tempItem, destClazz);
List<T> result = new ArrayList<>(source.size());
for (Object item : source){
result.add(copyBean(beanCopier, item, destClazz));
}
return result;
}
return null;
}

private static <T> BeanCopier getCopier(Object source, Class<T> destClazz) {
return getCopier(source.getClass(), destClazz);
}

private static <T> BeanCopier getCopier(Object source, T t) {
return getCopier(source.getClass(), t.getClass());
}

private static <T> BeanCopier getCopier(Class<?> sourceClazz, Class<T> destClazz){
String copierName = sourceClazz.getName()+"&"+destClazz.getName();
BeanCopier beanCopier = beanCopierConcurrentHashMap.get(copierName);
if (beanCopier == null){
beanCopier = BeanCopier.create(sourceClazz, destClazz, false);
beanCopierConcurrentHashMap.put(copierName, beanCopier);
}
return beanCopier;
}

private static <T> T copyBean(BeanCopier beanCopier, Object source, Class<T> destClazz) throws IllegalAccessException, InstantiationException {
T t = destClazz.newInstance();
return copyBean(beanCopier, source, t);
}

private static <T> T copyBean(BeanCopier beanCopier, Object source, T t) {
beanCopier.copy(source, t, null);
return t;
}
}
  • 发表于 2019-03-08 12:00
  • 阅读 ( 505 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除