jdk24怎么使用import com.sun.source.tree.*; import com.sun.tools.javac.api.*; import com.sun.tools.javac.code.*; import com.sun.tools.javac.processing.*; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.util.*;现在Fatal error compiling: java.lang.IllegalAccessError: class io.github.dengchen.processor.BeanCopyApt (in unnamed module @0x3bf73251) cannot access class com.sun.tools.javac.api.JavacTrees (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.api to unnamed module @0x3bf73251 -> [Help 1]
时间: 2025-07-21 13:38:08 浏览: 6
### 三级标题:JDK 24 中使用 `com.sun.tools.javac.api.JavacTrees` 出现 `IllegalAccessError` 的解决方法
在 JDK 24 中,由于模块系统(JPMS)对内部 API 的访问限制更加严格,直接使用 `com.sun.tools.javac.api.JavacTrees` 等内部类时会触发 `java.lang.IllegalAccessError` 异常。这是因为 `jdk.compiler` 模块默认不再导出 `com.sun.tools.javac.processing` 或 `com.sun.tools.javac.main` 等内部包给未命名模块[^1]。
为了解决这一问题,可以通过在 JVM 启动参数中添加 `--add-exports` 来显式开放这些内部包的访问权限。例如,在运行 Maven 编译任务时,可以配置 `maven-compiler-plugin` 插件,向其添加 JVM 参数:
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
<arg>--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
</compilerArgs>
</configuration>
</plugin>
```
如果使用 Gradle 构建工具,则可以在 `build.gradle` 文件中通过 `jvmArgs` 配置 Java 编译器的启动参数:
```groovy
tasks.withType(JavaCompile) {
options.fork = true
options.forkOptions.jvmArgs += [
'--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED'
]
}
```
此外,某些依赖库(如 Lombok、Kapt)也依赖于这些内部 API。在这种情况下,建议确保使用的库版本与当前 JDK 兼容,或者手动升级到支持 JDK 24 的版本[^2]。若无法更新依赖库,可考虑降级 JDK 版本至 JDK 8,以避免模块系统的访问限制问题[^3]。
对于 IDE 环境(如 IntelliJ IDEA),还需要检查其运行时所使用的 JDK 是否为预期版本,并通过设置 VM Options 显式开放相关模块的访问权限。例如,在 IDEA 的 `idea64.vmoptions` 文件中添加以下内容:
```
--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED
```
---
阅读全文
相关推荐


















