Java反射的优雅使用

本文最后更新于:2023年9月2日 晚上

安卓9开始限制反射的调用,但是带系统签名或者内置系统的应用是可以豁免的 。

或者使用第三方库突破这个限制:

tiann/FreeReflection: A library that lets you use reflection without any restriction above Android P

如何使用

假设有一个Person类

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
package com.wesley.app;

public class Person {
private String name;
private int age;

private static int num = 0;

public Person(String name, int age) {
this.name = name;
this.age = age;
num++;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
this.age = age;
}
}

替换一个实例中的字段

1
2
3
4
5
6
Person person = new Person("Wesley", 25);
try {
Reflector.with(person).field("age").set(28);
} catch (Reflector.ReflectedException e) {
e.printStackTrace();
}

调用一个实例中对应的方法

1
2
3
4
5
6
7
8
try {
//无参数
Reflector.with(person).method("getAge").call();
//有参数
Reflector.with(person).method("setAge", int.class).call(26);
} catch (Reflector.ReflectedException e) {
e.printStackTrace();
}

获取静态变量

1
2
3
4
5
try {
Reflector.on(Person.class).field("num").get();
} catch (Reflector.ReflectedException e) {
e.printStackTrace();
}

生成实例对象

1
2
3
4
5
try {
Person tom = Reflector.on(Person.class).constructor(String.class, int.class).newInstance("Tom", 18);
} catch (Reflector.ReflectedException e) {
e.printStackTrace();
}

调用通过反射生成的实例的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
try {
Reflector reflector = Reflector.on(Person.class);
Person tom = reflector.constructor(String.class, int.class).newInstance("Tom", 18);

reflector.field("age").get(tom);
reflector.method("getAge").callByCaller(tom);
//或者
reflector.bind(tom);
reflector.field("age").get();
reflector.method("getAge").call();
} catch (Reflector.ReflectedException e) {
e.printStackTrace();
}

Reflector工具类

https://github.com/didi/VirtualAPK/blob/master/CoreLibrary/src/main/java/com/didi/virtualapk/utils/Reflector.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package com.wesley.sdk.helper.util;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
* Created by qiaopu on 2018/4/26.
*/
public class Reflector {

public static final String TAG = "Reflector";

protected Class<?> mType;
protected Object mCaller;
protected Constructor mConstructor;
protected Field mField;
protected Method mMethod;

public static class ReflectedException extends Exception {

public ReflectedException(String message) {
super(message);
}
public ReflectedException(String message, Throwable cause) {
super(message, cause);
}

}
public static Reflector on(@NonNull String name) throws ReflectedException {
return on(name, true, Reflector.class.getClassLoader());
}

public static Reflector on(@NonNull String name, boolean initialize) throws ReflectedException {
return on(name, initialize, Reflector.class.getClassLoader());
}

public static Reflector on(@NonNull String name, boolean initialize, @Nullable ClassLoader loader) throws ReflectedException {
try {
return on(Class.forName(name, initialize, loader));
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

public static Reflector on(@NonNull Class<?> type) {
Reflector reflector = new Reflector();
reflector.mType = type;
return reflector;
}

public static Reflector with(@NonNull Object caller) throws ReflectedException {
return on(caller.getClass()).bind(caller);
}

protected Reflector() {

}

public Reflector constructor(@Nullable Class<?>... parameterTypes) throws ReflectedException {
try {
mConstructor = mType.getDeclaredConstructor(parameterTypes);
mConstructor.setAccessible(true);
mField = null;
mMethod = null;
return this;
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

@SuppressWarnings("unchecked")
public <R> R newInstance(@Nullable Object ... initargs) throws ReflectedException {
if (mConstructor == null) {
throw new ReflectedException("Constructor was null!");
}
try {
return (R) mConstructor.newInstance(initargs);
} catch (InvocationTargetException e) {
throw new ReflectedException("Oops!", e.getTargetException());
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

protected Object checked(@Nullable Object caller) throws ReflectedException {
if (caller == null || mType.isInstance(caller)) {
return caller;
}
throw new ReflectedException("Caller [" + caller + "] is not a instance of type [" + mType + "]!");
}

protected void check(@Nullable Object caller, @Nullable Member member, @NonNull String name) throws ReflectedException {
if (member == null) {
throw new ReflectedException(name + " was null!");
}
if (caller == null && !Modifier.isStatic(member.getModifiers())) {
throw new ReflectedException("Need a caller!");
}
checked(caller);
}

public Reflector bind(@Nullable Object caller) throws ReflectedException {
mCaller = checked(caller);
return this;
}

public Reflector unbind() {
mCaller = null;
return this;
}

public Reflector field(@NonNull String name) throws ReflectedException {
try {
mField = findField(name);
mField.setAccessible(true);
mConstructor = null;
mMethod = null;
return this;
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

protected Field findField(@NonNull String name) throws NoSuchFieldException {
try {
return mType.getField(name);
} catch (NoSuchFieldException e) {
for (Class<?> cls = mType; cls != null; cls = cls.getSuperclass()) {
try {
return cls.getDeclaredField(name);
} catch (NoSuchFieldException ex) {
// Ignored
}
}
throw e;
}
}

@SuppressWarnings("unchecked")
public <R> R get() throws ReflectedException {
return get(mCaller);
}

@SuppressWarnings("unchecked")
public <R> R get(@Nullable Object caller) throws ReflectedException {
check(caller, mField, "Field");
try {
return (R) mField.get(caller);
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

public Reflector set(@Nullable Object value) throws ReflectedException {
return set(mCaller, value);
}

public Reflector set(@Nullable Object caller, @Nullable Object value) throws ReflectedException {
check(caller, mField, "Field");
try {
mField.set(caller, value);
return this;
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

public Reflector method(@NonNull String name, @Nullable Class<?>... parameterTypes) throws ReflectedException {
try {
mMethod = findMethod(name, parameterTypes);
mMethod.setAccessible(true);
mConstructor = null;
mField = null;
return this;
} catch (NoSuchMethodException e) {
throw new ReflectedException("Oops!", e);
}
}

protected Method findMethod(@NonNull String name, @Nullable Class<?>... parameterTypes) throws NoSuchMethodException {
try {
return mType.getMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
for (Class<?> cls = mType; cls != null; cls = cls.getSuperclass()) {
try {
return cls.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException ex) {
// Ignored
}
}
throw e;
}
}

public <R> R call(@Nullable Object... args) throws ReflectedException {
return callByCaller(mCaller, args);
}

@SuppressWarnings("unchecked")
public <R> R callByCaller(@Nullable Object caller, @Nullable Object... args) throws ReflectedException {
check(caller, mMethod, "Method");
try {
return (R) mMethod.invoke(caller, args);
} catch (InvocationTargetException e) {
throw new ReflectedException("Oops!", e.getTargetException());
} catch (Throwable e) {
throw new ReflectedException("Oops!", e);
}
}

public static class QuietReflector extends Reflector {

protected Throwable mIgnored;

public static QuietReflector on(@NonNull String name) {
return on(name, true, QuietReflector.class.getClassLoader());
}

public static QuietReflector on(@NonNull String name, boolean initialize) {
return on(name, initialize, QuietReflector.class.getClassLoader());
}

public static QuietReflector on(@NonNull String name, boolean initialize, @Nullable ClassLoader loader) {
Class<?> cls = null;
try {
cls = Class.forName(name, initialize, loader);
return on(cls, null);
} catch (Throwable e) {
// Log.w(LOG_TAG, "Oops!", e);
return on(cls, e);
}
}

public static QuietReflector on(@Nullable Class<?> type) {
return on(type, (type == null) ? new ReflectedException("Type was null!") : null);
}

private static QuietReflector on(@Nullable Class<?> type, @Nullable Throwable ignored) {
QuietReflector reflector = new QuietReflector();
reflector.mType = type;
reflector.mIgnored = ignored;
return reflector;
}

public static QuietReflector with(@Nullable Object caller) {
if (caller == null) {
return on((Class<?>) null);
}
return on(caller.getClass()).bind(caller);
}

protected QuietReflector() {

}

public Throwable getIgnored() {
return mIgnored;
}

protected boolean skip() {
return skipAlways() || mIgnored != null;
}

protected boolean skipAlways() {
return mType == null;
}

@Override
public QuietReflector constructor(@Nullable Class<?>... parameterTypes) {
if (skipAlways()) {
return this;
}
try {
mIgnored = null;
super.constructor(parameterTypes);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return this;
}

@Override
public <R> R newInstance(@Nullable Object... initargs) {
if (skip()) {
return null;
}
try {
mIgnored = null;
return super.newInstance(initargs);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return null;
}

@Override
public QuietReflector bind(@Nullable Object obj) {
if (skipAlways()) {
return this;
}
try {
mIgnored = null;
super.bind(obj);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return this;
}

@Override
public QuietReflector unbind() {
super.unbind();
return this;
}

@Override
public QuietReflector field(@NonNull String name) {
if (skipAlways()) {
return this;
}
try {
mIgnored = null;
super.field(name);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return this;
}

@Override
public <R> R get() {
if (skip()) {
return null;
}
try {
mIgnored = null;
return super.get();
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return null;
}

@Override
public <R> R get(@Nullable Object caller) {
if (skip()) {
return null;
}
try {
mIgnored = null;
return super.get(caller);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return null;
}

@Override
public QuietReflector set(@Nullable Object value) {
if (skip()) {
return this;
}
try {
mIgnored = null;
super.set(value);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return this;
}

@Override
public QuietReflector set(@Nullable Object caller, @Nullable Object value) {
if (skip()) {
return this;
}
try {
mIgnored = null;
super.set(caller, value);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return this;
}

@Override
public QuietReflector method(@NonNull String name, @Nullable Class<?>... parameterTypes) {
if (skipAlways()) {
return this;
}
try {
mIgnored = null;
super.method(name, parameterTypes);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return this;
}

@Override
public <R> R call(@Nullable Object... args) {
if (skip()) {
return null;
}
try {
mIgnored = null;
return super.call(args);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return null;
}

@Override
public <R> R callByCaller(@Nullable Object caller, @Nullable Object... args) {
if (skip()) {
return null;
}
try {
mIgnored = null;
return super.callByCaller(caller, args);
} catch (Throwable e) {
mIgnored = e;
// Log.w(LOG_TAG, "Oops!", e);
}
return null;
}
}
}