The Java Module System (JPMS)
Since Java 9, code can be grouped into modules. A module declares which other modules it needs and which of its packages others may use; everything else is hidden, even from reflection. This page explains readability, accessibility and module resolution, then builds a three-module project and shows services, compiler and startup errors, the class path difference, reflection with opens, jdeps and jlink.
Contents
Why modules exist
Before Java 9, all JARs on the class path formed one flat namespace. A publicsun.misc.Unsafe
The Java Platform Module System (JPMS, JSR 376, Java 9) added a level above packages. A module has a name, a list of modules it requiresexports
Two checks make this work. Readability: module A can use module B only if A requiresrequires transitive
| JDK | JEP | Change |
|---|---|---|
| 9 | JEP 200, 201, 261, 282 | Modular JDK, module system, jlink |
| 11 | JEP 320 | Java EE and CORBA modules removed from the JDK |
| 16 | JEP 396 | JDK internals strongly encapsulated by default |
| 17 | JEP 403 | The option to relax that (--illegal-access |
| 25 | JEP 511 | import module M; |
The JDK was the first big user. The program below inspects the running JDK's own modules.
import java.lang.module.ModuleDescriptor;
import java.util.Set;
public class JdkModules {
public static void main(String[] args) {
// The JDK itself is split into modules
Set<Module> boot = ModuleLayer.boot().modules();
System.out.println("modules in the boot layer: " + boot.size());
Module base = Object.class.getModule();
ModuleDescriptor d = base.getDescriptor();
long toAll = d.exports().stream().filter(e -> !e.isQualified()).count();
long toSome = d.exports().size() - toAll;
System.out.println(base.getName() + ": " + d.packages().size() + " packages, "
+ toAll + " exported to everyone, " + toSome + " only to named JDK modules");
for (String pkg : new String[] {"java.lang", "java.util", "jdk.internal.misc",
"sun.nio.ch"}) {
System.out.printf(" %-18s exported to everyone: %b%n", pkg,
base.isExported(pkg));
}
// Code on the class path lives in the unnamed module
System.out.println("this class: named module? " + JdkModules.class.getModule().isNamed());
}
}
Output (JDK 21, run from the class path; the counts differ between JDK versions):
modules in the boot layer: 62
java.base: 196 packages, 54 exported to everyone, 67 only to named JDK modules
java.lang exported to everyone: true
java.util exported to everyone: true
jdk.internal.misc exported to everyone: false
sun.nio.ch exported to everyone: false
this class: named module? false
Of the 196 packages in java.basejava.langjava.utiljdk.internal.misc
A three-module project
To see the rules in action, here is a small shop application split into three modules, each in its own directory under src/module-info.java
| Module | Role | Packages |
|---|---|---|
com.shop.api | The PaymentService | com.shop.apicom.shop.api.internal |
com.shop.impl | A card payment implementation | com.shop.impl |
com.shop.app | The main program | com.shop.app |
// src/com.shop.api/module-info.java
module com.shop.api {
exports com.shop.api; // public API: readable by other modules
// com.shop.api.internal is not exported, so it stays private to this module
}
// src/com.shop.api/com/shop/api/PaymentService.java
package com.shop.api;
import com.shop.api.internal.Money;
public interface PaymentService {
String name();
String pay(long cents);
static String format(long cents) {
return Money.format(cents); // the API module can use its own internal package
}
}
// src/com.shop.api/com/shop/api/internal/Money.java
package com.shop.api.internal;
public final class Money {
private Money() {
}
public static String format(long cents) {
return String.format("%d.%02d", cents / 100, cents % 100);
}
}
// src/com.shop.impl/module-info.java
module com.shop.impl {
requires com.shop.api;
provides com.shop.api.PaymentService with com.shop.impl.CardPayment;
// no exports: other modules can only reach CardPayment through ServiceLoader
}
// src/com.shop.impl/com/shop/impl/CardPayment.java
package com.shop.impl;
import com.shop.api.PaymentService;
public class CardPayment implements PaymentService {
@Override
public String name() {
return "card";
}
@Override
public String pay(long cents) {
return "charged " + PaymentService.format(cents) + " to card";
}
}
// src/com.shop.app/module-info.java
module com.shop.app {
requires com.shop.api;
uses com.shop.api.PaymentService;
}
// src/com.shop.app/com/shop/app/Main.java
package com.shop.app;
import com.shop.api.PaymentService;
import java.lang.reflect.Field;
import java.util.ServiceLoader;
public class Main {
public static void main(String[] args) throws Exception {
Module me = Main.class.getModule();
System.out.println("running in module: " + me.getName());
System.out.println("reads com.shop.api: "
+ me.canRead(PaymentService.class.getModule()));
// The implementation is found without this module naming or requiring it
int found = 0;
for (PaymentService service : ServiceLoader.load(PaymentService.class)) {
found++;
System.out.println("found service '" + service.name() + "' in module "
+ service.getClass().getModule().getName() + ": " + service.pay(1999));
}
System.out.println("services found: " + found);
// Reflection cannot open up a package that was not exported or opened
Class<?> money = Class.forName("com.shop.api.internal.Money");
try {
Object result = money.getMethod("format", long.class).invoke(null, 5L);
System.out.println("calling internal Money.format: allowed, returned " + result);
} catch (IllegalAccessException e) {
System.out.println("calling internal Money.format: IllegalAccessException");
}
// The same rule protects the JDK's own internals
Field value = String.class.getDeclaredField("value");
try {
value.setAccessible(true);
System.out.println("String.value setAccessible: allowed");
} catch (java.lang.reflect.InaccessibleObjectException e) {
System.out.println("String.value setAccessible: InaccessibleObjectException");
}
}
}
All three modules are compiled in one command with --module-source-path-m module/mainclass
javac -d out --module-source-path src $(find src -name '*.java')
java --module-path out -m com.shop.app/com.shop.app.Main
Output:
running in module: com.shop.app
reads com.shop.api: true
found service 'card' in module com.shop.impl: charged 19.99 to card
services found: 1
calling internal Money.format: IllegalAccessException
String.value setAccessible: InaccessibleObjectException
requires only the API module, yetcom.shop.app foundServiceLoader . Because the app declaresCardPayment and the impl module declaresuses PaymentService , the JVM adds the provider module when it resolves the application. The app has no compile-time dependency on the implementation.provides ... with CardPayment is aMoney class with apublic method, but its package is not exported, so reflection from another module getspublic .IllegalAccessException on a private field ofsetAccessible(true) fails withString , becauseInaccessibleObjectException does not openjava.base for deep reflection. In Java 9 to 15 this only printed a warning. Java 16 made it an error by default, and Java 17 (JEP 403) removed the option to switch back.java.lang
What the compiler checks
Strong encapsulation starts at compile time. Adding this class to the app module, which imports the internal package:
package com.shop.app;
import com.shop.api.internal.Money;
class Bad {
String x = Money.format(5);
}
makes the build fail:
src/com.shop.app/com/shop/app/Bad.java:3: error: package com.shop.api.internal is not visible
import com.shop.api.internal.Money;
^
(package com.shop.api.internal is declared in module com.shop.api, which does not export it)
1 error
A missing requiresNoClassDefFoundError
java --module-path out --describe-module com.shop.api
java --module-path out --describe-module com.shop.impl
com.shop.api file://.../out/com.shop.api/
exports com.shop.api
requires java.base mandated
contains com.shop.api.internal
com.shop.impl file://.../out/com.shop.impl/
requires java.base mandated
requires com.shop.api
provides com.shop.api.PaymentService with com.shop.impl.CardPayment
contains com.shop.impl
Every module implicitly requires java.basecontains
Startup checks: missing modules and split packages
On the class path, a missing JAR shows up as NoClassDefFoundErrormain
java --module-path out/com.shop.app:out/com.shop.impl -m com.shop.app/com.shop.app.Main
Error occurred during initialization of boot layer
java.lang.module.FindException: Module com.shop.api not found, required by com.shop.app
The JVM refused to start and named both the missing module and the module that needs it. The second rule concerns split packages: a package may live in only one module. A small separate project has two library modules that both contain com.shop.util
javac -d out --module-source-path src $(find src -name '*.java')
split/src/app.main/module-info.java:1: error: module app.main reads package com.shop.util from both lib.one and lib.two
module app.main {
^
1 error
On the class path the two copies would silently merge, and whichever JAR came first would win for each class. Split packages are the most common obstacle when moving old libraries to the module path; the fix is to rename one package or merge the modules.
Class path versus module path
Modules are opt-in. The same compiled classes can be run the old way, on the class path:
java -cp out/com.shop.app:out/com.shop.api:out/com.shop.impl com.shop.app.Main
running in module: null
reads com.shop.api: true
services found: 0
calling internal Money.format: allowed, returned 0.05
String.value setAccessible: InaccessibleObjectException
Everything changed except the last line:
- All classes are now in the unnamed module, so the module name is
.null - No services were found. On the class path,
readsServiceLoader files, notMETA-INF/services clauses, and this project has none.provides - The "internal"
class is reachable: the module boundaries ofMoney no longer exist.com.shop.api - The JDK's own encapsulation still applies, because the JDK is always modular.
JARs without a module-info.classAutomatic-Module-Name
Reflection, frameworks and opens
Frameworks such as Jackson, Hibernate and Spring read and write private fields by reflection. An exported package is not enough for that: exportsopensOrder
// src/com.shop.model/module-info.java
module com.shop.model {
exports com.shop.model; // exported, but not opened for deep reflection
}
// src/com.shop.model/com/shop/model/Order.java
package com.shop.model;
public class Order {
private final String id = "A-17"; // private, as entity and DTO fields usually are
private final long cents = 4250;
public Order() {
}
}
// src/com.shop.mapper/module-info.java
module com.shop.mapper {
requires com.shop.model;
}
// src/com.shop.mapper/com/shop/mapper/Mapper.java
package com.shop.mapper;
import com.shop.model.Order;
import java.lang.reflect.Field;
// What a JSON or ORM framework does: read private fields by reflection
public class Mapper {
public static void main(String[] args) throws Exception {
Order order = new Order();
StringBuilder json = new StringBuilder("{");
for (Field f : Order.class.getDeclaredFields()) {
try {
f.setAccessible(true);
json.append('"').append(f.getName()).append("\":\"").append(f.get(order))
.append("\",");
} catch (RuntimeException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
return;
}
}
json.setCharAt(json.length() - 1, '}');
System.out.println(json);
}
}
Run as it is, and then with the package opened from the command line:
java --module-path out -m com.shop.mapper/com.shop.mapper.Mapper
InaccessibleObjectException: Unable to make field private final java.lang.String com.shop.model.Order.id accessible: module com.shop.model does not "opens com.shop.model" to module com.shop.mapper
java --module-path out --add-opens com.shop.model/com.shop.model=com.shop.mapper \
-m com.shop.mapper/com.shop.mapper.Mapper
{"id":"A-17","cents":"4250"}
- The first run failed with
, and the message spells out the fix: moduleInaccessibleObjectException does not "opens com.shop.model" tocom.shop.model . This is the error people meet when they first put a JPA or JSON library on the module path.com.shop.mapper - With
the same code produced--add-opens . In your own module, write{"id":"A-17","cents":"4250"} inopens com.shop.model to com.fasterxml.jackson.databind; instead, so the permission lives with the code.module-info.java is also the escape hatch for libraries that still reflect on JDK internals, such as--add-opens . Treat each one as technical debt to remove.--add-opens java.base/java.lang=ALL-UNNAMED
All module directives
| Directive | Meaning |
|---|---|
requires M | This module reads module M and can use its exported packages |
requires transitive M | Modules that require this one also read M (for types that appear in this module's API) |
requires static M | Needed at compile time, optional at run time |
exports p | Public types in package p are usable by other modules, but not their private members via reflection |
exports p to M | Exported only to the listed modules |
opens p | Allows deep reflection on package p at run time (for frameworks such as Jackson, Hibernate, Spring), without compile-time access |
open module M | Opens every package for reflection |
uses S | This module looks up implementations of service S with ServiceLoader |
provides S with C | Class C implements service S |
When a framework fails with InaccessibleObjectExceptionopens--add-opens
Finding dependencies with jdeps
jdepsmodule-info.java
jdeps -s --module-path out out/com.shop.app out/com.shop.impl out/com.shop.api
com.shop.api -> java.base
com.shop.app -> com.shop.api
com.shop.app -> java.base
com.shop.impl -> com.shop.api
com.shop.impl -> java.base
jdeps --module-path out --print-module-deps out/com.shop.app
com.shop.api,java.base
The summary shows the expected graph: the app and the implementation depend on the API, and everything depends on java.base--print-module-depsjlink --add-modulesjdeps --jdk-internals
Custom runtimes with jlink
Because the JDK and the application are both modules, jlink
jlink --module-path out --add-modules com.shop.app,com.shop.impl \
--output image --strip-debug --no-header-files --no-man-pages
image/bin/java --list-modules
com.shop.api
com.shop.app
com.shop.impl
java.base@21.0.12.1
image/bin/java -m com.shop.app/com.shop.app.Main
running in module: com.shop.app
reads com.shop.api: true
found service 'card' in module com.shop.impl: charged 19.99 to card
...
The image contains the three application modules and java.base--add-modules--bind-services
Should your application use modules?
| Situation | Recommendation |
|---|---|
| A library used by many projects | At least set Automatic-Module-Namemodule-info.class |
| A large application with internal layers | Modules make the layering enforceable; start with the leaf modules |
| An application with many non-modular dependencies | Stay on the class path, or use automatic modules as a bridge |
| Small container images or desktop distribution | jlinkjdeps --print-module-deps |
Framework reflection fails with InaccessibleObjectException | opensmodule-info.java--add-opens |
| Pluggable implementations | usesprovidesServiceLoader |
Even an application that stays on the class path is affected by modules, because the JDK's own encapsulation always applies. For how classes are found and loaded in both modes, see