-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertUtils.java
More file actions
91 lines (70 loc) · 2.92 KB
/
ConvertUtils.java
File metadata and controls
91 lines (70 loc) · 2.92 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
package egovframework.api.admin.utils;
import java.lang.reflect.Field;
import java.util.*;
public class ConvertUtils {
public ConvertUtils() {}
public static Map<String, Object> convertToMap(Object obj) {
try {
if (Objects.isNull(obj)) {
return Collections.emptyMap();
}
Map<String, Object> convertMap = new HashMap<>();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
convertMap.put(field.getName(), field.get(obj));
}
return convertMap;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T convertToValueObject(Map<String, Object> map, Class<T> type) {
try {
Objects.requireNonNull(type, "Class cannot be null");
T instance = type.getConstructor().newInstance();
if (map == null || map.isEmpty()) {
return instance;
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
Field[] fields = type.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String name = field.getName();
Class<? extends Object> entryType = entry.getValue().getClass();
Class<? extends Object> fieldType = field.getType();
boolean isSameType = entryType.equals(fieldType);
boolean isSameName = entry.getKey().equals(name);
if (isSameType && isSameName) {
field.set(instance, map.get(name));
break;
}
}
}
return instance;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static List<Map<String, Object>> convertToMaps(List<?> list) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
List<Map<String, Object>> convertList = new ArrayList<>(list.size());
for (Object obj : list) {
convertList.add(ConvertUtils.convertToMap(obj));
}
return convertList;
}
public static <T> List<T> convertToValueObjects(List<HashMap<String, Object>> list, Class<T> type) {
Objects.requireNonNull(type, "Class cannot be null");
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
List<T> convertList = new ArrayList<>(list.size());
for (Map<String, Object> map : list) {
convertList.add(ConvertUtils.convertToValueObject(map, type));
}
return convertList;
}
}