Dealing with Reflection-Heavy Frameworks
You'll learn how to make your modular code work seamlessly with frameworks like Spring and Hibernate that rely heavily on runtime reflection.
The Reflection Problem in JPMS
Many popular frameworks—Spring, Hibernate, Jackson, JUnit—need to inspect and manipulate your classes at runtime through reflection. They instantiate objects, call private methods, and access fields that weren't designed for public use. JPMS's strong encapsulation breaks this by default, even when you've exported packages.
Think of it like this: Exporting a package is like publishing your public API in a catalog—anyone can see it and use it normally. But frameworks often need backstage access to peek behind the curtain at private implementation details. That's where opens comes in.
Using opens for Framework Access
When a framework needs reflective access to your internal types, use the opens directive:
module my.app {
requires spring.context;
requires hibernate.core;
exports com.myapp.api; // Normal public API
opens com.myapp.entities; // Let frameworks reflect on entities
opens com.myapp.config to spring.core; // Limit access to Spring only
}
The opens directive grants deep reflection access without making the package part of your public API. Qualified opens...to restricts access to specific frameworks you trust.
When to Use Each Approach
- Use
exportsfor your intended public API - Use
opensfor internal packages that frameworks must access reflectively - Use
open module(sparingly!) if the entire module needs to be reflection-transparent - Use qualified
opens...towhen you know exactly which framework needs access
Key Takeaway: Use opens or opens...to directives to grant reflection access to framework-heavy packages without exposing them as part of your module's public API—allowing Spring, Hibernate, and similar tools to work while maintaining strong encapsulation boundaries.