对象拷贝

2019-03-10 11:56:11来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折


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;
}
}

原文链接:https://www.cnblogs.com/gavin-yao/p/10494336.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:springboot 2.0.8 跳转jsp页面

下一篇:SpringMVC_01:创建运行环境(Maven)