提交 | 用户 | 时间
|
a6de49
|
1 |
/** |
H |
2 |
* Copyright (c) 2018 人人开源 All rights reserved. |
|
3 |
* |
|
4 |
* https://www.renren.io |
|
5 |
* |
|
6 |
* 版权所有,侵权必究! |
|
7 |
*/ |
|
8 |
|
|
9 |
package com.iailab.framework.common.util.object; |
|
10 |
|
|
11 |
import org.slf4j.Logger; |
|
12 |
import org.slf4j.LoggerFactory; |
|
13 |
import org.springframework.beans.BeanUtils; |
|
14 |
|
|
15 |
import java.lang.reflect.Field; |
|
16 |
import java.util.ArrayList; |
|
17 |
import java.util.Arrays; |
|
18 |
import java.util.Collection; |
|
19 |
import java.util.List; |
|
20 |
|
|
21 |
/** |
|
22 |
* 转换工具类 |
|
23 |
* |
|
24 |
* @author Mark sunlightcs@gmail.com |
|
25 |
*/ |
|
26 |
public class ConvertUtils { |
|
27 |
private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class); |
|
28 |
|
|
29 |
public static <T> T sourceToTarget(Object source, Class<T> target){ |
|
30 |
if(source == null){ |
|
31 |
return null; |
|
32 |
} |
|
33 |
T targetObject = null; |
|
34 |
try { |
|
35 |
targetObject = target.newInstance(); |
|
36 |
BeanUtils.copyProperties(source, targetObject); |
|
37 |
} catch (Exception e) { |
|
38 |
logger.error("convert error ", e); |
|
39 |
} |
|
40 |
|
|
41 |
return targetObject; |
|
42 |
} |
|
43 |
|
|
44 |
public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){ |
|
45 |
if(sourceList == null){ |
|
46 |
return null; |
|
47 |
} |
|
48 |
|
|
49 |
List targetList = new ArrayList<>(sourceList.size()); |
|
50 |
try { |
|
51 |
for(Object source : sourceList){ |
|
52 |
T targetObject = target.newInstance(); |
|
53 |
BeanUtils.copyProperties(source, targetObject); |
|
54 |
targetList.add(targetObject); |
|
55 |
} |
|
56 |
}catch (Exception e){ |
|
57 |
logger.error("convert error ", e); |
|
58 |
} |
|
59 |
|
|
60 |
return targetList; |
|
61 |
} |
|
62 |
/** |
|
63 |
* 获取类的所有属性,包括父类 |
|
64 |
* |
|
65 |
* @param object |
|
66 |
* @return |
|
67 |
*/ |
|
68 |
public static Field[] getAllFields(Object object) { |
|
69 |
Class<?> clazz = object.getClass(); |
|
70 |
List<Field> fieldList = new ArrayList<>(); |
|
71 |
while (clazz != null) { |
|
72 |
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); |
|
73 |
clazz = clazz.getSuperclass(); |
|
74 |
} |
|
75 |
Field[] fields = new Field[fieldList.size()]; |
|
76 |
fieldList.toArray(fields); |
|
77 |
return fields; |
|
78 |
} |
|
79 |
} |