-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
ReflectUtil.java
84 lines (74 loc) · 2.23 KB
/
ReflectUtil.java
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
package nallar.tickthreading.util;
import nallar.tickthreading.Log;
import nallar.unsafe.UnsafeUtil;
import java.lang.reflect.*;
import java.util.*;
public enum ReflectUtil {
;
public static Field getField(Class c, String name) {
Field field = null;
do {
try {
field = c.getDeclaredField(name);
} catch (NoSuchFieldException ignored) {
}
} while (field == null && (c = c.getSuperclass()) != Object.class);
if (field != null) {
field.setAccessible(true);
}
return field;
}
private static Method getMethod(Class c, String name) {
Method method = null;
do {
for (Method method_ : c.getDeclaredMethods()) {
if (method_.getName().equals(name)) {
if (method != null) {
Log.severe("Two possible matches: " + method + ", " + method_);
}
method = method_;
}
}
} while (method == null && (c = c.getSuperclass()) != Object.class);
method.setAccessible(true);
return method;
}
public static <T> T get(Object o, String fieldName) {
try {
return (T) getField(o.getClass(), fieldName).get(o);
} catch (IllegalAccessException e) {
throw UnsafeUtil.throwIgnoreChecked(e);
}
}
public static <T> T call(Object o, String methodName, Object... args) {
try {
return (T) getMethod(o.getClass(), methodName).invoke(o, args);
} catch (Throwable t) {
throw UnsafeUtil.throwIgnoreChecked(t);
}
}
public static int getInt(Object o, String fieldName) {
try {
return getField(o.getClass(), fieldName).getInt(o);
} catch (IllegalAccessException e) {
throw UnsafeUtil.throwIgnoreChecked(e);
}
}
public static Field[] getFields(Class<?> clazz, Class<?> fieldType) {
List<Field> listFields = new ArrayList<Field>();
List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
for (Field field : fields) {
if (fieldType.isAssignableFrom(field.getType())) {
listFields.add(field);
}
}
return listFields.toArray(new Field[listFields.size()]);
}
public static Field getField(final Class<?> inClass, final Class<?> type, final int index) {
Field[] fields = getFields(inClass, type);
if (fields == null || fields.length <= index) {
return null;
}
return fields[index];
}
}