Open Modules: Making All Packages Reflectively Accessible
You'll learn how to use the open modifier to make an entire module reflectively accessible without listing individual packages.
The Core Idea
Instead of adding opens directives for each package individually, you can declare an open module by placing the open keyword before module in your module-info.java. This automatically makes every package in the module open for deep reflection to all other modules—as if you had written opens for each one.
Think of it like this: a regular module is a house where you must unlock each room (package) individually for reflection access. An open module is a house where all doors are unlocked by default.
Syntax
open module com.example.reflective {
requires java.base;
exports com.example.api;
// No need for individual opens directives
// ALL packages are reflectively accessible
}
When to Use Open Modules
Open modules are ideal for:
- Frameworks and libraries designed specifically for reflection-heavy operations (serialization, dependency injection, testing frameworks)
- Legacy code migration where many packages need reflection access during the transition to JPMS
- Situations where most or all packages require
opensanyway
What It Doesn't Change
- Exported packages remain exported via
exportsdirectives - Non-exported packages stay inaccessible at compile-time—
openonly affects runtime reflection - You still control readability with
requires
Key Takeaway: The open module modifier is a convenience that applies opens behavior to all packages automatically, making the entire module reflectively accessible without sacrificing compile-time encapsulation of non-exported packages.