/
ReflectUtil.java
237 lines (216 loc) · 6.71 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package cn.xdean.jex.reflect;
import cn.xdean.jex.lang.ExceptionUtil;
import java.lang.reflect.*;
import java.util.*;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class ReflectUtil {
private static final UnaryOperator<Executable> EXECUTABLE_GET_ROOT;
private static final Function<Class<?>, Method[]> CLASS_GET_ROOT_METHODS;
private static final UnaryOperator<Field> FIELD_GET_ROOT;
private static final Function<Class<?>, Field[]> CLASS_GET_ROOT_FIELDS;
static {
try {
Method getRootMethod = Executable.class.getDeclaredMethod("getRoot");
getRootMethod.setAccessible(true);
EXECUTABLE_GET_ROOT = m -> ExceptionUtil.uncheck(() -> (Executable) getRootMethod.invoke(m));
Method getRootMethods = Class.class.getDeclaredMethod("privateGetPublicMethods");
getRootMethods.setAccessible(true);
CLASS_GET_ROOT_METHODS = c -> ExceptionUtil.uncheck(() -> (Method[]) getRootMethods.invoke(c));
Field getRootField = Field.class.getDeclaredField("root");
getRootField.setAccessible(true);
FIELD_GET_ROOT = f -> ExceptionUtil.uncheck(() -> (Field) getRootField.get(f));
Method getRootFields = Class.class.getDeclaredMethod("privateGetPublicFields", Set.class);
getRootFields.setAccessible(true);
CLASS_GET_ROOT_FIELDS = c -> ExceptionUtil.uncheck(() -> (Field[]) getRootFields.invoke(c, new Object[] { null }));
} catch (NoSuchMethodException | SecurityException | NoSuchFieldException e) {
throw new IllegalStateException("ReflectUtil init fail, check your java version.", e);
}
}
public static void setModifiers(AccessibleObject ao, int modifier) {
Arrays.stream(getAllFields(ao.getClass()))
.filter(f -> f.getName().equals("modifiers"))
.peek(f -> f.setAccessible(true))
.forEach(f -> ExceptionUtil.uncheck(() -> f.set(ao, modifier)));
}
/**
* Get root of the method.
*/
public static Method getRootMethod(Method m) {
return getRootExecutable(m);
}
/**
* Get root of the executable.
*/
@SuppressWarnings("unchecked")
public static <T extends Executable> T getRootExecutable(T m) {
return (T) EXECUTABLE_GET_ROOT.apply(m);
}
/**
* Get root public methods of the class.
*/
public static Method[] getRootMethods(Class<?> clz) {
return CLASS_GET_ROOT_METHODS.apply(clz);
}
/**
* Get root of the field.
*/
public static Field getRootField(Field f) {
return FIELD_GET_ROOT.apply(f);
}
/**
* Get root public fields of the class.
*/
public static Field[] getRootFields(Class<?> clz) {
return CLASS_GET_ROOT_FIELDS.apply(clz);
}
/**
* Get field value by name
*
* @param clz
* @param t
* @param fieldName
* @return
* @throws NoSuchFieldException
*/
@SuppressWarnings("unchecked")
public static <T, O> O getFieldValue(Class<T> clz, T t, String fieldName) throws NoSuchFieldException {
Field field = clz.getDeclaredField(fieldName);
field.setAccessible(true);
try {
return (O) field.get(t);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Get all fields
*
* @param clz
* @param includeStatic include static fields or not
* @return
*/
public static Field[] getAllFields(Class<?> clz, boolean includeStatic) {
return Arrays.stream(getAllFields(clz))
.filter(f -> includeStatic || !Modifier.isStatic(f.getModifiers()))
.toArray(Field[]::new);
}
/**
* Get all fields
*
* @param clz
* @return
*/
public static Field[] getAllFields(Class<?> clz) {
List<Field> list = new ArrayList<>();
do {
list.addAll(Arrays.asList(clz.getDeclaredFields()));
} while ((clz = clz.getSuperclass()) != null);
return list.toArray(new Field[list.size()]);
}
/**
* Get all methods
*
* @param clz
* @return
*/
public static Method[] getAllMethods(Class<?> clz) {
Set<Method> set = new HashSet<>();
List<Class<?>> classes = new ArrayList<>();
classes.add(clz);
classes.addAll(Arrays.asList(getAllSuperClasses(clz)));
classes.addAll(Arrays.asList(getAllInterfaces(clz)));
for (Class<?> c : classes) {
set.addAll(Arrays.asList(c.getDeclaredMethods()));
}
return set.toArray(new Method[set.size()]);
}
/**
* Get all super classes
*
* @param clz
* @return
*/
public static Class<?>[] getAllSuperClasses(Class<?> clz) {
List<Class<?>> list = new ArrayList<>();
while ((clz = clz.getSuperclass()) != null) {
list.add(clz);
}
return list.toArray(new Class<?>[list.size()]);
}
/**
* Get all interfaces
*
* @param clz
* @return
*/
public static Class<?>[] getAllInterfaces(Class<?> clz) {
HashSet<Class<?>> set = new HashSet<>();
getAllInterfaces(clz, set);
return set.toArray(new Class<?>[set.size()]);
}
private static void getAllInterfaces(Class<?> clz, Set<Class<?>> visited) {
if (clz.getSuperclass() != null) {
getAllInterfaces(clz.getSuperclass(), visited);
}
for (Class<?> c : clz.getInterfaces()) {
if (visited.add(c)) {
getAllInterfaces(c, visited);
}
}
}
/**
* Get the name of the class who calls the caller.<br>
* For example. The following code will print "A".
*
* <pre>
* <code>class A {
* static void fun() {
* B.fun();
* }
* }
*
* class B {
* static void fun() {
* System.out.println(ReflectUtil.getCallerClassName());
* }
* }</code>
* </pre>
*
* @return
*/
public static String getCallerClassName() {
return getCaller().getClassName();
}
public static StackTraceElement getCaller() {
return getCaller(1, true);
}
/**
* Get caller stack info.
*
* @param deep Deep to search the caller class.If deep is 0, it returns the class who calls this
* method.
* @param ignoreSameClass If it is true, calling in same class will be ignored.
*/
public static StackTraceElement getCaller(int deep, boolean ignoreSameClass) {
// index 0 is Thread.getStackTrace
// index 1 is ReflectUtil.getCallerClassName
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
StackTraceElement currentStack = stElements[1];
int found = deep + 1;
for (int i = 1; i < stElements.length; i++) {
StackTraceElement nextStack = stElements[i];
if (nextStack.getClassName().equals(ReflectUtil.class.getName())) {
continue;
}
if (!ignoreSameClass || !currentStack.getClassName().equals(nextStack.getClassName())) {
currentStack = nextStack;
found--;
}
if (found == 0) {
return currentStack;
}
}
throw new IllegalArgumentException("Stack don't have such deep.");
}
}