对象拷贝
作者:互联网
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;
}
}
标签:return,BeanCopier,对象,source,static,beanCopier,拷贝,destClazz 来源: https://www.cnblogs.com/gavin-yao/p/10494336.html