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 public class was visible to every other class, so a library had no way to keep helper packages private, and applications came to depend on JDK internals such as sun.misc.Unsafe. Missing JARs were discovered only when a class failed to load at run time.

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 requires, and a list of packages it exports. The rules are checked by the compiler and enforced by the JVM, including against reflection.

Two checks make this work. Readability: module A can use module B only if A requires B, directly or through a requires transitive chain. Accessibility: even then, A can use only the public types in packages that B exports. When the JVM starts, it resolves the module graph from the main module: it finds every required module on the module path, adds service providers, and stops with an error if a module is missing or two modules contain the same package. Only then does any application code run.

The module system, by version
JDKJEPChange
9JEP 200, 201, 261, 282Modular JDK, module system, jlink
11JEP 320Java EE and CORBA modules removed from the JDK
16JEP 396JDK internals strongly encapsulated by default
17JEP 403The option to relax that (--illegal-access) removed
25JEP 511import module M; imports every package a module exports

The JDK was the first big user. The program below inspects the running JDK's own modules.

Java
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):

Output
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.base, only 54 are open to all code, such as java.lang and java.util. Others, like jdk.internal.misc, are exported only to specific JDK modules, so application code cannot use them. A class started from the class path, like this one, belongs to the unnamed module.

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/ with a module-info.java at its root:

The example modules
ModuleRolePackages
com.shop.apiThe PaymentService interfacecom.shop.api (exported), com.shop.api.internal (hidden)
com.shop.implA card payment implementationcom.shop.impl (hidden)
com.shop.appThe main programcom.shop.app
Java
// 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);
    }
}
Java
// 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";
    }
}
Java
// 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, and the application is started from the module path with -m module/mainclass:

Output
javac -d out --module-source-path src $(find src -name '*.java')
java --module-path out -m com.shop.app/com.shop.app.Main

Output:

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
  1. com.shop.app requires only the API module, yet ServiceLoader found CardPayment. Because the app declares uses PaymentService and the impl module declares provides ... with CardPayment, the JVM adds the provider module when it resolves the application. The app has no compile-time dependency on the implementation.
  2. Money is a public class with a public method, but its package is not exported, so reflection from another module gets IllegalAccessException.
  3. setAccessible(true) on a private field of String fails with InaccessibleObjectException, because java.base does not open java.lang 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.

What the compiler checks

Strong encapsulation starts at compile time. Adding this class to the app module, which imports the internal package:

Java
package com.shop.app;

import com.shop.api.internal.Money;

class Bad {
    String x = Money.format(5);
}

makes the build fail:

Output
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 requires is also a compile error, and a missing module is reported when the JVM starts rather than as a NoClassDefFoundError in the middle of a run. You can ask the JVM what a compiled module declares:

Output
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.base ("mandated"). contains lists the packages that are present but not exported.

Startup checks: missing modules and split packages

On the class path, a missing JAR shows up as NoClassDefFoundError whenever the first class from it is needed, which can be hours into a run. On the module path, the whole graph is checked before main starts. Here the application is launched with the API module left off the module path:

Output
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, and an application that requires both:

Output
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:

Output
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, ServiceLoader reads META-INF/services files, not provides clauses, and this project has none.
  • The "internal" Money class is reachable: the module boundaries of com.shop.api no longer exist.
  • The JDK's own encapsulation still applies, because the JDK is always modular.

JARs without a module-info.class can also be put on the module path. They become automatic modules, named after the Automatic-Module-Name manifest entry or the file name, which export all their packages and read every other module. This is the usual bridge while dependencies are not yet modularized.

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: exports grants access to public members at compile time and run time, while deep reflection on private members needs opens. A third small project has a model module with an Order class and a mapper module that turns it into JSON by reflection, as a framework would:

Java
// 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() {
    }
}
Java
// 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:

Output
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 InaccessibleObjectException, and the message spells out the fix: module com.shop.model does not "opens com.shop.model" to com.shop.mapper. This is the error people meet when they first put a JPA or JSON library on the module path.
  • With --add-opens the same code produced {"id":"A-17","cents":"4250"}. In your own module, write opens com.shop.model to com.fasterxml.jackson.databind; in module-info.java instead, so the permission lives with the code.
  • --add-opens is also the escape hatch for libraries that still reflect on JDK internals, such as --add-opens java.base/java.lang=ALL-UNNAMED. Treat each one as technical debt to remove.

All module directives

module-info.java directives
DirectiveMeaning
requires MThis module reads module M and can use its exported packages
requires transitive MModules that require this one also read M (for types that appear in this module's API)
requires static MNeeded at compile time, optional at run time
exports pPublic types in package p are usable by other modules, but not their private members via reflection
exports p to MExported only to the listed modules
opens pAllows deep reflection on package p at run time (for frameworks such as Jackson, Hibernate, Spring), without compile-time access
open module MOpens every package for reflection
uses SThis module looks up implementations of service S with ServiceLoader
provides S with CClass C implements service S

When a framework fails with InaccessibleObjectException on your own classes, the fix is usually an opens directive for the package it reflects on, or --add-opens on the command line for code you do not control.

Finding dependencies with jdeps

jdeps analyses compiled classes and reports which modules they depend on, which is the first step both for writing a module-info.java and for choosing what goes into a custom runtime:

Output
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-deps prints the same set as one comma-separated line, ready to paste into jlink --add-modules. Run on an old class-path JAR, jdeps --jdk-internals lists every use of encapsulated JDK internals that will fail on Java 17 and later.

Custom runtimes with jlink

Because the JDK and the application are both modules, jlink can compute exactly which modules are needed and build a runtime image that contains only those:

Output
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
Output
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, nothing else. On the machine used for this page it takes 52 MB, compared with 287 MB for the full JDK 21 installation, and it ran the program, service lookup included, without any separate Java installation. The implementation module had to be named in --add-modules because jlink, unlike the launcher, does not add service providers by default; the --bind-services option does that.

Should your application use modules?

Choosing between the class path and the module path
SituationRecommendation
A library used by many projectsAt least set Automatic-Module-Name in the manifest; ideally ship a module-info.class
A large application with internal layersModules make the layering enforceable; start with the leaf modules
An application with many non-modular dependenciesStay on the class path, or use automatic modules as a bridge
Small container images or desktop distributionjlink with jdeps --print-module-deps, which also works for class-path apps that need only JDK modules
Framework reflection fails with InaccessibleObjectExceptionopens in your module-info.java, or --add-opens for code you do not own
Pluggable implementationsuses and provides with ServiceLoader; see ServiceLoader

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 class loading.