工具-Bean检查

bean检查是否含有非静态内部类

gson对非静态内部类(没有默认构造函数)会有问题

作者提了一种检查方法:运行时去匹配,运行时去拿到model对象的包路径下所有的class对象,然后做规则匹配

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
public class PureInnerClassDetector {
private static final String sPackageNeedDetect = "com.example.zhanghongyang.blog01.model";

public static void startDetect(Application context) {

try {
final Set<String> classNames = new HashSet<>();
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
File sourceApk = new File(applicationInfo.sourceDir);
DexFile dexfile = new DexFile(sourceApk);
Enumeration<String> dexEntries = dexfile.entries();
while (dexEntries.hasMoreElements()) {
String className = dexEntries.nextElement();
Log.d("zhy-blog", "detect " + className);
if (className.startsWith(sPackageNeedDetect)) {
if (isPureInnerClass(className)) {
classNames.add(className);
}
}
}
if (!classNames.isEmpty()) {
for (String className : classNames) {
// crash ?
Log.e("zhy-blog", "编写非静态内部类被发现:" + className);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

private static boolean isPureInnerClass(String className) {
if (!className.contains("$")) {
return false;
}
try {
Class<?> aClass = Class.forName(className);
Field $this0 = aClass.getDeclaredField("this$0");
if (!$this0.isSynthetic()) {
return false;
}
// 其他匹配条件
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

}