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;
}
}
对象拷贝
import org.springframework.cglib.beans.BeanCopier;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;/** * @ClassName: BeanCopyUtils * @...
- 发表于 2019-03-08 12:00
- 阅读 ( 505 )
- 分类:网络文章
你可能感兴趣的文章
随机文章
- Appium Error :Exception in thread “main” org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session 1365 浏览
- Drag and drop in Recyclerview using itemTouchViewer without affecting the animation 203 浏览
- Why do I get “File could only be replicated to 0 nodes” when writing to a partitioned table? 328 浏览
- PostgreSQL - How to get data grouped by two columns? 219 浏览
- Validate if email address exists in JavaScript [duplicate] 257 浏览
相关问题
条评论
请先 登录 后评论
发送私信
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!