在Java 9引入模块化系统后,模块之间的访问权限被严格管控,反射作为打破封装的常用手段,很容易因为模块未开放对应包的访问权限而触发非法访问异常。当opens声明缺失时,即使代码在类路径下可以正常运行,迁移到模块化项目后也会抛出相关错误。

常见异常表现
opens声明缺失导致的反射异常通常会有明确的报错信息,常见的内容如下:
java.lang.IllegalAccessException: class com.example.caller.Caller (in module caller.module) cannot access class com.example.target.Secret (in module target.module) because module target.module does not open com.example.target to caller.module at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361) at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:361) at java.base/java.lang.reflect.Field.setAccessible(Field.java:180)
报错信息中已经明确指出了问题模块和目标包,这是排查的核心线索。
排查步骤
1. 定位异常触发点的模块和包
首先查看异常堆栈的第一行,找到抛出异常的模块和无法访问的类所在的包。比如上面的例子中,目标类是com.example.target.Secret,所在包是com.example.target,所属模块是target.module,调用方模块是caller.module。
2. 检查目标模块的module-info.java
打开target.module模块的module-info.java文件,查看是否已经对com.example.target包做了opens声明。如果文件中只有exports声明而没有opens声明,反射调用就会失败,因为exports仅允许普通类访问,不包括反射的深层访问。
3. 确认opens声明的适用范围
opens声明有两种形式,需要根据调用方的类型选择:
- 无条件开放:
opens com.example.target;,开放给所有模块,包括未命名模块(类路径下的代码) - 定向开放:
opens com.example.target to caller.module;,仅开放给指定的caller.module模块
如果调用方是未命名模块(比如旧的没有模块化的jar包),必须使用无条件开放的形式。
正确配置示例
假设目标模块target.module的module-info.java原本内容如下:
module target.module {
// 仅导出包,不允许反射访问
exports com.example.target;
}
如果需要允许caller.module模块通过反射访问该包下的类,修改为:
module target.module {
exports com.example.target;
// 定向开放给caller.module模块
opens com.example.target to caller.module;
}
如果是需要允许所有模块(包括未命名模块)反射访问,修改为:
module target.module {
exports com.example.target;
// 无条件开放包
opens com.example.target;
}
注意事项
opens声明仅对反射生效,普通的对象实例化、方法调用不需要opens,只需要exports即可。如果混淆了exports和opens的用法,就会导致不必要的权限开放,或者出现本例中的访问异常。另外,如果模块中使用了open module的声明形式,那么该模块下所有包都会默认开放反射访问权限,不需要单独写opens声明。
// 该模块下所有包都允许反射访问
open module target.module {
exports com.example.target;
}
Java模块化反射opens声明IllegalAccessException修改时间:2026-06-10 07:48:11