如何在jshell中使用jdk.compiler模块



我的jdk版本是17,我想使用com.sun.tools.javac.file.JavacFileManager类,我的启动参数是

$ jshell --add-modules jdk.compiler

然后输入

import com.sun.tools.javac.file.JavacFileManager;

我得到了这样的错误:

|  Error:
|  package com.sun.tools.javac.file is not visible
|    (package com.sun.tools.javac.file is declared in module jdk.compiler, which does not export it to the unnamed module)
|  import com.sun.tools.javac.file.JavacFileManager;
|         ^----------------------^

我该怎么办?

从JEP 403开始不允许访问JDK内部模块。要在Java 17中显式地允许访问,可以在启动JVM时使用--add-exports选项。这个选项似乎也与jshel:

jshell --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED

--add-exports文档在这里:

--add-exports module/package=target-module(,target-module)*
Updates module to export package to target-module, regardless of module declaration. The target-module can be all unnamed to export to all unnamed modules. 

最新更新