如何在jdk9 / java-9中使用sun.reflect包?
问题描述:
我正在使用jdk-9,我想在我的代码中使用 sun.reflect。*
包但我得到以下异常
I am using jdk-9 and I want to use sun.reflect.*
package in my code but I am getting the below exception
Exception in thread 'main' java.lang.IllegalAccessError : class Test (in moudle: Unnamed Module) cannot access class sun.reflect.Reflaction (in module:java.base), sun.reflect is not exported to Unnamed module
当我使用下面的示例代码运行时JDK-9
when I run below sample code using JDK-9
public static void main(String args[]){
System.out.println(Reflection.getCallerClass(3));
}
答
适用于较新的OpenJDK 9 EA构建。例如:
Works fine with newer OpenJDK 9 EA builds. For example:
$ java -version
java version "9-ea"
Java(TM) SE Runtime Environment (build 9-ea+138)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+138, mixed mode)
$ javac Test.java
Test.java:5: warning: Reflection is internal proprietary API and may be removed in a future release
System.out.println(Reflection.getCallerClass(3));
^
Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 warning
$ java Test
null
似乎已将其修复为9-ea + 115版本,作为 JDK-8137058 。所以你可能正在使用旧的EA版本。一般来说,@ Holger是对的:这个API很有可能在将来的Java版本中完全消失,所以请考虑迁移到StackWalker API。
Seems that it was fixed in 9-ea+115 build as a part of JDK-8137058. So probably you are using older EA build. In general @Holger is right: there are big chances that this API will disappear completely in future Java versions, so consider migrating to StackWalker API.