103. Java Platform Module System (JPMS)
Project Jigsaw introduced JPMS and module-info.java, replacing brittle classpaths with explicit module dependencies, strong encapsulation, and reflection barriers.
Explanation
Before Java 9, Java applications relied on the flat classpath. If two JARs contained classes with the same package name or conflicting versions, the JVM picked whichever JAR appeared first on -cp ("JAR Hell"). Furthermore, public in Java meant accessible to everyone across the entire JVM โ internal implementation classes could not be shielded from library users.
The Java Platform Module System (JPMS) introduces the module: a named, self-describing collection of code and resources defined by a module-info.java descriptor. Key directives: - requires <module>;: Specifies a compile-time and runtime dependency. - requires transitive <module>;: Dependents of this module implicitly require that module too. - exports <package>;: Makes public types in the package accessible to outside modules. Non-exported packages are strictly encapsulated, even against reflection! - opens <package> [to <module>];: Permits deep reflection (e.g. for Spring, Jackson, Hibernate) without exposing packages at compile time. - provides <Service> with <Implementation>; and uses <Service>;: Modular ServiceLoader mechanism.
JPMS also modularized the JDK itself into java.base, java.sql, java.desktop, etc., allowing developers to use jlink to build customized, minimal runtimes (often 30โ50MB instead of 300MB+).
Example
// File: module-info.java
module com.example.orderservice {
// 1. Explicit dependencies
requires java.sql;
requires transitive com.example.common;
// 2. Export public API to all consumers
exports com.example.orderservice.api;
// 3. Allow reflection only for JSON serialization (e.g., Jackson)
opens com.example.orderservice.dto to com.fasterxml.jackson.databind;
// 4. Expose service provider implementation
provides com.example.common.PaymentProcessor
with com.example.orderservice.impl.StripePaymentProcessor;
// 5. Declare service consumption
uses com.example.common.NotificationService;
}Sources
- https://dev.java/learn/modules/ โ dev.java Java Modules Guide
- https://openjdk.org/jeps/261 โ JEP 261: Module System