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 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
65
66
67
68
69
70
71
72 static boolean isExported(final Class<?> declarator) {
73 if (IS_EXPORTED != null) {
74 try {
75 final Object module = GET_MODULE.invoke(declarator);
76 if (module != null) {
77 final String pkgName = (String) GET_PKGNAME.invoke(declarator);
78 return (Boolean) IS_EXPORTED.invoke(module, pkgName);
79 }
80 } catch (final Throwable e) {
81
82 }
83 }
84 return true;
85 }
86
87
88
89
90
91
92
93 static String getPackageName(final Class<?> clz) {
94 String pkgName = "";
95 if (clz != null) {
96
97 if (GET_PKGNAME != null) {
98 try {
99 return (String) GET_PKGNAME.invoke(clz);
100 } catch (final Throwable xany) {
101 return "";
102 }
103 }
104
105 Class<?> clazz = clz;
106 while (clazz.isArray()) {
107 clazz = clazz.getComponentType();
108 }
109
110 if (clazz.isPrimitive()) {
111 return "java.lang";
112 }
113
114 Class<?> walk = clazz.getEnclosingClass();
115 while (walk != null) {
116 clazz = walk;
117 walk = walk.getEnclosingClass();
118 }
119 final Package pkg = clazz.getPackage();
120
121 if (pkg == null) {
122 final String name = clazz.getName();
123 final int dot = name.lastIndexOf('.');
124 if (dot > 0) {
125 pkgName = name.substring(0, dot);
126 }
127 } else {
128 pkgName = pkg.getName();
129 }
130 }
131 return pkgName;
132 }
133
134 }