java.lang.IllegalAccessError:类X(在模块Y中)无法访问类Z(在模块W中),因为模块W未将Z导出到模块Y
java.lang.IllegalAccessError: class X (in module Y) cannot access class Z (in module W) because module W does not export Z to module Y
ID: java/illegalaccesserror-module-does-not-export
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Java 9 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
| OpenJDK 11.0.20 | active | — | — | — |
根因分析
在Java 9+模块系统中发生,当一个模块中的类尝试通过反射访问另一个模块中的类,而目标模块未导出该包时,通常由于缺少'--add-exports'或'--add-opens' JVM标志。
English
This error occurs in Java 9+ module system when a class from one module tries to reflectively access a class from another module that does not export the package, typically due to missing '--add-exports' or '--add-opens' JVM flags.
官方文档
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/IllegalAccessError.html解决方案
-
Add JVM flags: `--add-opens java.base/java.lang=ALL-UNNAMED` to open the package to all unnamed modules. For example: `java --add-opens java.base/java.lang=ALL-UNNAMED -jar myapp.jar`
-
Update the module-info.java of your application to add 'requires' and 'exports' directives: `requires java.base; exports com.example.myapp to some.module;`
-
As a temporary workaround, run the application on the classpath (remove module-info.java) to bypass module system restrictions entirely.
无效尝试
常见但无效的做法:
-
Adding the dependency to pom.xml or build.gradle to include the missing module
80% 失败
The error is not about missing dependencies; it's about module access control. Adding the dependency does not grant reflective access to internal packages.
-
Setting the classpath to include all jars without module declarations
70% 失败
If the application runs as a named module (e.g., with module-info.java), classpath changes do not override module access restrictions.
-
Recompiling the library with public modifiers on the target class
90% 失败
The error is about module exports, not Java access modifiers; even public classes in non-exported packages are inaccessible.