All 15 Java Platform Module System (JPMS) questions
More in Java Platform Module System (JPMS)
Advertisement
Java › Java Platform Module System (JPMS)

What is a qualified export (exports package to specificModule), and when would you use it instead of a plain, unqualified export?

Intermediate

Answer

A qualified export (exports package.name to module1, module2) makes a package accessible ONLY to the specifically named target module(s), rather than to every module that might require yours -- this is useful for exposing an internal-ish package needed by a small number of closely-related, trusted modules (like a testing module needing access to internals for white-box testing, or an internal SPI implementation module) without making that package part of your module's genuinely public, broadly-supported API surface, striking a middle ground between full encapsulation and full public exposure.
module com.example.core {
    exports com.example.core.api;  // fully public, unqualified
    exports com.example.core.internal to com.example.core.test, com.example.core.plugin;
    // 'internal' package accessible ONLY to these two specific, trusted modules -- not to the general public
}
Real-world example A library's internal package containing implementation details needed by its own dedicated test module (for white-box testing of private-ish logic) uses a qualified export granting access specifically to that test module by name, keeping the package genuinely hidden from all other, unrelated consumer modules that only need the library's standard public API.

Common follow-ups: Why might a qualified export still be considered a form of tight coupling between modules, even though it's more restrictive than a full export?;How would you add an additional trusted target module to an existing qualified export later, if a new legitimate consumer emerges?