After Java 9 modularization, reflection cannot access classes in the JDK. #619
Closed
abing22333
started this conversation in
General
Replies: 1 comment 1 reply
-
public static void main(String[] args) throws ClassNotFoundException {
Class<?> c = Class.forName("java.lang.Throwable");
System.out.println(getFieldGenericType(c, "cause"));
}
private static String getFieldGenericType(Class c, String fileName) {
try {
Field f = c.getDeclaredField(fileName);
f.setAccessible(true);
Type t = f.getGenericType();
return t.getTypeName();
} catch (NoSuchFieldException e) {
return null;
}
} The above code will throw a java.lang.reflect.InaccessibleObjectException when run with Java 16+ version. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Regarding issue #615 (Error in generating SSE long-connection interface under JDK17)
关于issue #615 (在JDK17下,生成SSE长连接接口报错)
Root Cause(根本原因)
The modularization feature introduced since Java 9 has begun to gradually encapsulate the internal structure of the JDK. Starting with Java 16, it is no longer possible to directly use reflection to access classes within the JDK.
是从Java9引入模块化特性以后,开始逐步强封装JDK内部结构。Java 16开始无法直接使用反射访问JDK中类。
JEP 396: Strongly Encapsulate JDK Internals by Default (Java 16 )
Summary
By default, all internal elements of the JDK are strongly encapsulated, except for critical internal APIs such as sun.misc.Unsafe. It allows end-users to opt for the looser strong encapsulation that has been the default since JDK 9.
默认情况下对 JDK 的所有内部元素进行强封装,关键的内部 API(如 sun.misc.Unsafe)除外。允许最终用户选择自 JDK 9 以来一直默认的宽松强封装
JEP 403: Strongly Encapsulate JDK Internals (Java 17)
Summary:
All internal elements of the JDK are strongly encapsulated, except for key internal APIs such as sun.misc.Unsafe. It is no longer possible, as it was from JDK 9 to JDK 16, to relax the strong encapsulation of internal elements through a command-line option.
强封装 JDK 的所有内部元素,关键内部 API(如 sun.misc.Unsafe)除外。不再可能像 JDK 9 到 JDK 16 那样,通过一个命令行选项来放松对内部元素的强封装。
Temporary Solution(临时解决方案)
https://zhuanlan.zhihu.com/p/435449372
https://stackoverflow.com/questions/66974846/java-lang-exceptionininitializererror-with-java-16-j-l-classformaterror-access/67006749#67006749
##Final Solution(最终解决方案)
Personally, I believe that the framework should address this issue, rather than having users add parameters. However, it seems that cglib has not resolved this issue either.
个人认为应该是框架来解决这个问题,而不是让用户添加参数。 不过发现cglib也没有解决这个问题
Beta Was this translation helpful? Give feedback.
All reactions