-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReflectionUtils.java
More file actions
91 lines (81 loc) · 3.11 KB
/
ReflectionUtils.java
File metadata and controls
91 lines (81 loc) · 3.11 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 utils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;
public class ReflectionUtils {
public static Map<String, String> objectToFieldsMap(Object obj) {
Map params = new HashMap();
Class objCls = obj.getClass();
try {
Collection<Field> fields = getFields(objCls);
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
/*if(field.isAnnotationPresent(RequestParam.class)){
name = field.getAnnotation(RequestParam.class).getName();
}*/
field.setAccessible(true);
Object value = null;
value = getValue(obj, field, value);
params.put(name, value == null ? "" : value.toString());
}
}
return params;
} catch (Exception e) {
return params;
}
}
public static String getObjectString(Object obj) {
Class<?> objCls = obj.getClass();
Field[] employeeFields = objCls.getDeclaredFields();
Field[] cEmployeeFields = objCls.getSuperclass().getDeclaredFields();
Field[] allFields = new Field[employeeFields.length + cEmployeeFields.length];
Arrays.setAll(allFields, new IntFunction<Field>() {
@Override
public Field apply(int value) {
return value < employeeFields.length ? employeeFields[value] : cEmployeeFields[value - employeeFields.length];
}
});
StringBuilder sb = new StringBuilder();
sb.append("param begins\n");
for (Field field : allFields) {
if (!Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
field.setAccessible(true);
Object value = null;
value = getValue(obj, field, value);
sb.append(name);
sb.append(" :: ");
sb.append(value == null ? "" : value.toString());
sb.append("\n");
}
}
sb.append("param ends\n");
return sb.toString();
}
private static Object getValue(Object obj, Field field, Object value) {
try {
value = field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return value;
}
private static Collection<Field> getFields(Class<?> objCls) {
HashMap fields;
for (fields = new HashMap(); objCls != null; objCls = objCls.getSuperclass()) {
Field[] declaredFields = objCls.getDeclaredFields();
int length = declaredFields.length;
for (Field field : declaredFields) {
if (!fields.containsKey(field.getName())) {
fields.put(field.getName(), field);
}
}
}
return fields.values();
}
}