What is the Java Platform Module System (JPMS, introduced in Java 9), and what core problem does it aim to solve compared to the traditional classpath-based approach?
Short answer
JPMS introduces explicit, JVM-enforced modules (declared via a module-info.java file) as a higher-level organizational unit above individual packages/JARs, letting you explicitly declare a module's dependencies (requires) and what it exposes to other modules (exports) -- this…
Advertisement
AModel answer
JPMS introduces explicit, JVM-enforced modules (declared via a module-info.java file) as a higher-level organizational unit above individual packages/JARs, letting you explicitly declare a module's dependencies (requires) and what it exposes to other modules (exports) -- this solves several longstanding classpath-era problems: the lack of genuine encapsulation (any public class on the classpath was effectively visible to any other code, regardless of intended internal-only status), no explicit, verifiable dependency declarations (you couldn't easily tell what a JAR actually depended on without inspecting its code), and the notorious 'JAR hell' (multiple JARs on the classpath silently conflicting or providing incompatible versions of the same classes with no clear detection or resolution mechanism).
// module-info.java
module com.example.myapp {
requires java.sql; // explicit dependency declaration
requires com.example.shared;
exports com.example.myapp.api; // only this package is visible to other modules
// com.example.myapp.internal is NOT exported -- genuinely, JVM-enforced hidden
}Real-world example
A large enterprise application modularizes its previously monolithic classpath-based codebase into explicit JPMS modules, immediately surfacing several previously-invisible implicit dependencies between components that had been silently relying on classpath-wide visibility, forcing the team to make these dependencies explicit and properly declared.
Likely follow-ups
- How does JPMS's module-level encapsulation differ from and complement the class-level access modifiers (private, protected) that already existed before Java 9?
- What is the 'unnamed module', and how does traditional classpath-based code interact with the module system?
Related topics