Why opens Is Needed: Reflection and Encapsulation
What you'll learn: How JPMS's strong encapsulation blocks reflection by default and why the opens directive is necessary to restore reflective access.
The Problem: Strong Encapsulation Blocks Reflection
With JPMS, strong encapsulation doesn't just prevent compile-time access to non-exported packages—it also blocks runtime reflection by default. Even if a framework or library could previously use reflection to access private fields or invoke private methods (using setAccessible(true)), modules now prevent this.
This creates a challenge: many frameworks like Hibernate, Jackson, and Spring rely heavily on reflection to:
- Access private fields for serialization
- Instantiate objects via private constructors
- Read annotations on non-public members
Why exports Isn't Enough
The exports directive only grants compile-time visibility to public types. It does not grant deep reflective access. A framework can see your public API but still cannot use setAccessible(true) to break into private members—even in exported packages.
The Solution: opens
The opens directive explicitly grants reflective access to a package at runtime, allowing frameworks to:
- Call
setAccessible(true)on non-public members - Access private fields, methods, and constructors
- Maintain compatibility with reflection-heavy tools
Think of it like this: exports unlocks the front door (public API), while opens gives a master key that opens every room (deep reflection).
You can open entire packages or selectively open to specific modules, just like qualified exports.
Key Takeaway:
Strong encapsulation in modules blocks reflective access by default; use opens to explicitly permit frameworks and libraries to perform deep reflection on your internal implementation when necessary.