The Module System
Java 9 introduced the Java Platform Module System (JPMS), a layer of organization above packages. Where a package groups related classes, a module groups related packages and declares, explicitly, what it needs from the outside world and what it is willing to expose.
Declaring a Module
module-info.java
module com.example.orders {
requires java.sql;
requires com.example.billing;
exports com.example.orders.api;
}Directive | Meaning |
module com.example.orders | Declares this module's unique name |
requires java.sql | This module depends on the java.sql module |
requires com.example.billing | This module depends on another application module |
exports com.example.orders.api | Makes only this package's public types visible to other modules |
requires and exports
Why Modules Exist: Stronger Encapsulation
Aspect | Packages Alone (Classpath) | Modules (JPMS) |
Visibility of public classes | Visible to any code on the classpath | Visible only if the containing package is exported |
Dependency declaration | Implicit — anything on the classpath is reachable | Explicit — must be listed with requires |
Hiding internals | Not possible for public classes | Possible — keep a package un-exported |