警告:发生了非法的反射访问操作
WARNING: An illegal reflective access operation has occurred
ID: java/illegal-reflective-access-warning
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Java 9 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
根因分析
代码使用反射访问某个模块中类的成员,但该模块未将包导出给调用者,自 Java 9 起,Java 模块系统(JPMS)禁止此操作。
English
Code is using reflection to access a member of a class in a module that does not export the package to the caller, which is disallowed by the Java module system (JPMS) since Java 9.
官方文档
https://docs.oracle.com/en/java/javase/17/migrate/migration-guide.pdf解决方案
-
添加 JVM 参数以打开特定包:`--add-opens java.base/java.lang=ALL-UNNAMED`(根据需要替换模块和包)。
-
将库更新到使用正确模块导出或使用 `ModuleLayer` API 访问非导出包的版本。
-
如果你控制库,在 `module-info.java` 中添加 `exports` 指令,将包导出给调用者模块。
无效尝试
常见但无效的做法:
-
Add `--illegal-access=permit` JVM flag to allow all reflective access.
95% 失败
The `--illegal-access=permit` flag was removed in Java 17; it only works in Java 9-16. In Java 17+, it causes an error: 'Java.lang.IllegalArgumentException: IllegalAccessError'.
-
Set `AccessibleObject.setAccessible(true)` to bypass the warning.
80% 失败
The warning is generated by the JVM's reflective access check; setAccessible does not suppress the warning or fix the underlying module access issue.
-
Ignore the warning; it's just a warning.
70% 失败
In future Java versions, illegal reflective access will throw an `InaccessibleObjectException` at runtime, breaking the application.