Unable to export a package from java.base module

给你一囗甜甜゛ 提交于 2019-11-30 05:14:46
Stuart Marks

Nicolai's answer is correct regarding the techniques necessary to export an otherwise unexported package from the java.base module or from any other module.

But if the goal is to use Unsafe, the way to do so is to use sun.misc.Unsafe which is exported by the jdk.unsupported module. If you're compiling your code for the unnamed module, you needn't do anything special regarding modules to get access to it. If you're compiling code in a module, you need to add

requires jdk.unsupported;

to your module-info.java file.

To use Unsafe you have to do the reflective setAccessible technique to get access to the field, which is the same as you had to do in previous JDK releases:

import sun.misc.Unsafe;

...

Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeField.setAccessible(true);
Unsafe theUnsafe = (Unsafe)theUnsafeField.get(null);

Even though Unsafe is in the jdk.unsupported module, this technique is supported in JDK 9, in accordance with JEP 260.

The module java.base does not export the package jdk.internal.misc., so the type jdk.internal.misc.Unsafe is not accessible - as a consequence compilation fails.

You can make it export the package by adding the following command line option:

# if you want to access it from com.jigsaw.npe only:
--add-exports java.base/jdk.internal.misc=com.jigsaw.npe
# if you want to access from all code:
--add-exports java.base/jdk.internal.misc=ALL-UNNAMED

You will have to do that when compiling (javac) and when running (java) the code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!