Qualified opens: Opening Packages to Specific Modules
What you'll learn: How to grant reflective access to your packages only to trusted, specific modules rather than opening them to the entire module system.
The Core Idea
In the previous lesson, you learned about unconditional opens, which grants reflective access to a package to all modules. But what if you want tighter control? That's where qualified opens comes in.
Qualified opens lets you specify exactly which modules can perform deep reflection on your package. This follows the principle of least privilege: only the modules that genuinely need reflective access get it.
Syntax
The syntax mirrors qualified exports:
module com.myapp.data {
opens com.myapp.data.entities to
com.framework.persistence,
com.testing.framework;
}
This declaration says: "The package com.myapp.data.entities is opened for reflection, but only to com.framework.persistence and com.testing.framework."
Why This Matters
Think of it like a VIP list for a private event. Unconditional opens is an open-door policy—anyone can enter. Qualified opens is a guest list—only named invitees get in.
Common scenario: Your application uses a persistence framework (like Hibernate) that needs reflective access to your entity classes. You don't want every module in your application to have that power—just the persistence layer.
module com.shop.model {
opens com.shop.model.domain to
org.hibernate.core;
}
Now only Hibernate can reflect into com.shop.model.domain, maintaining encapsulation against other modules.
Combining with exports
You can export a package normally while also using qualified opens for reflection:
exports com.myapp.api;
opens com.myapp.api to com.serialization.lib;
Key Takeaway: Use opens...to to grant reflective access only to specific, trusted modules, maintaining stronger encapsulation than unconditional opens while still supporting frameworks that require reflection.