1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jexl3.internal.introspection;
18
19 import java.lang.invoke.MethodHandle;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.MethodType;
22
23
24
25
26 final class ClassTool {
27
28 private static final MethodHandle GET_MODULE;
29
30 private static final MethodHandle GET_PKGNAME;
31
32 private static final MethodHandle IS_EXPORTED;
33
34 static {
35 final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
36 MethodHandle getModule = null;
37 MethodHandle getPackageName = null;
38 MethodHandle isExported = null;
39 try {
40 final Class<?> modulec = ClassTool.class.getClassLoader().loadClass("java.lang.Module");
41 if (modulec != null) {
42 getModule = LOOKUP.findVirtual(Class.class, "getModule", MethodType.methodType(modulec));
43 if (getModule != null) {
44 getPackageName = LOOKUP.findVirtual(Class.class, "getPackageName", MethodType.methodType(String.class));
45 if (getPackageName != null) {
46 isExported = LOOKUP.findVirtual(modulec, "isExported", MethodType.methodType(boolean.class, String.class));
47 }
48 }
49 }
50 } catch (final Exception e) {
51
52 }
53 GET_MODULE = getModule;
54 GET_PKGNAME = getPackageName;
55 IS_EXPORTED = isExported;
56 }
57
58
59
60
61
62
63
64 static String getPackageName(final Class<?> clz) {
65 String pkgName = "";
66 if (clz != null) {
67
68 if (GET_PKGNAME != null) {
69 try {
70 return (String) GET_PKGNAME.invoke(clz);
71 } catch (final Throwable xany) {
72 return "";
73 }
74 }
75
76 Class<?> clazz = clz;
77 while (clazz.isArray()) {
78 clazz = clazz.getComponentType();
79 }
80
81 if (clazz.isPrimitive()) {
82 return "java.lang";
83 }
84
85 Class<?> walk = clazz.getEnclosingClass();
86 while (walk != null) {
87 clazz = walk;
88 walk = walk.getEnclosingClass();
89 }
90 final Package pkg = clazz.getPackage();
91
92 if (pkg == null) {
93 final String name = clazz.getName();
94 final int dot = name.lastIndexOf('.');
95 if (dot > 0) {
96 pkgName = name.substring(0, dot);
97 }
98 } else {
99 pkgName = pkg.getName();
100 }
101 }
102 return pkgName;
103 }
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119 static boolean isExported(final Class<?> declarator) {
120 if (IS_EXPORTED != null) {
121 try {
122 final Object module = GET_MODULE.invoke(declarator);
123 if (module != null) {
124 final String pkgName = (String) GET_PKGNAME.invoke(declarator);
125 return (Boolean) IS_EXPORTED.invoke(module, pkgName);
126 }
127 } catch (final Throwable e) {
128
129 }
130 }
131 return true;
132 }
133
134 }