Strong Encapsulation: What exports Protects
What you'll learn: How JPMS enforces ironclad encapsulation—non-exported packages remain completely hidden, even from reflection attempts.
The Fortress Wall of JPMS
Before modules, Java's encapsulation was more of a suggestion than a rule. Even private members could be accessed via setAccessible(true) through reflection. JPMS changes this fundamentally.
When you don't export a package in your module-info.java, that package becomes truly invisible to other modules. It's not just hidden—it's protected. No other module can:
- Import classes from that package
- Reference types from that package at compile time
- Access those classes via reflection at runtime (by default)
Think of it like a castle: exported packages are the gates you've deliberately opened to visitors. Non-exported packages are the private chambers—even if someone knows they exist, the walls prevent entry.
Reflection Is Blocked Too
This is the game-changer. Previously, frameworks could bypass access restrictions using reflection. With JPMS, strong encapsulation blocks reflection by default on non-exported packages. Calling setAccessible(true) on classes in unexported packages will fail with an InaccessibleObjectException unless you explicitly open those packages.
The exports directive creates a security perimeter. If com.myapp.internal isn't exported, external modules simply cannot see it—not through normal access, not through reflection, not at all.
Why This Matters
Strong encapsulation lets you:
- Hide implementation details with confidence
- Refactor internal code without breaking external dependencies
- Prevent accidental misuse of internal APIs
- Improve security by restricting what code can introspect
Key Takeaway: JPMS's exports directive enforces strong encapsulation—non-exported packages are truly inaccessible to other modules, even via reflection, making your module boundaries enforceable at both compile time and runtime.