BeanConvert.java
2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.yoho.unions.convert;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author xieyong
*
*/
@Component
public class BeanConvert implements Convert{
private final Logger log = LoggerFactory.getLogger(getClass());
//拷贝不支持对象里面嵌套对象拷贝
/* (non-Javadoc)
* @see com.yoho.product.convert.Convert#convertFrom(java.lang.Object, java.lang.Object, java.lang.Class)
*/
@SuppressWarnings("unchecked")
@Override
public final <T> T convertFrom(Object source, Object target, Class<T> clazz) {
if (source == null){
return null;
}
Preconditions.checkNotNull(target, "target can't be null");
BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), false);
copier.copy(source, target, null);
return (T) target;
}
/**
* 将多个对象拷贝到一个目的对象, 不需要实例化目的对象
*
* @param targetClazz 目的对象的CLASS
* @param sources 源对象
* @param <T> 目的对象类型
*
* @return 目的对象实例, 拷贝之后的结果
* @author create by DengXinFei 2016-1-23
*/
public static <T>T copyBeans(Class<T> targetClazz, Object... sources){
if(null == sources || sources.length == 0){
return null;
}
T targetObj = null;
try{
targetObj = targetClazz.newInstance();
for(Object sourceObj: sources){
BeanCopier copier = BeanCopier.create(sourceObj.getClass(), targetClazz, false);
copier.copy(sourceObj, targetObj, null);
}
}catch(Exception e){
e.printStackTrace();
return null;
}
return targetObj;
}
/* (non-Javadoc)
* @see com.yoho.product.convert.Convert#convertFromList(java.util.List, java.lang.Class)
*/
@SuppressWarnings("unchecked")
@Override
public final <T> List<T> convertFromList(List<? extends Object> sourceList,Class<T> clazz) {
if(CollectionUtils.isEmpty(sourceList))
{
return new ArrayList<T>(0);
}
BeanCopier copier = BeanCopier.create(sourceList.get(0).getClass(), clazz, false);
List<T> list=Lists.newArrayList();
//这里反射性能可能不佳,要测试
try
{
Object target=null;
for (Object t : sourceList) {
target=clazz.newInstance();
copier.copy(t, target, null);
list.add((T)target);
}
}
catch (Exception e) {
log.error("other exception" ,e);
throw new RuntimeException("other exception",e);
}
return list;
}
}