Skip to content
Tutorials Center
My learning

Topics

Lesson 156 of 201 ยท JVM and Advanced Topics

The Java Module System (JPMS)

Learn the Java Platform Module System - module-info.java, requires, exports, opens and services, strong encapsulation, the module path, and custom runtimes with jlink.

Packages organize classes, and access modifiers control who can use them. But there's a gap: a public class is public to everyone. If your library has a package com.shop.pricing.internal with public helper classes (because other packages of your own library need them), any application can use them too, and once they do, you can never change them without breaking someone.

The Java Platform Module System (JPMS, introduced in Java 9) closes that gap. A module is a named group of packages with a descriptor, module-info.java, that says which other modules it needs and which of its packages it makes available. Everything else is hidden, even public classes, and the JVM enforces it at compile time and at run time. The JDK itself is split into about 70 modules, which is why you can build a small custom Java runtime with only the parts your application uses.

This lesson explains the module descriptor, strong encapsulation, reflection with opens, services, how modular and non-modular code coexist, and jlink. Because our editor runs a single file, the examples do something unusual: each one writes real module-info.java files to a temporary folder, compiles them with the JDK's built-in compiler API, and loads the result into a new module layer. The modules are real; only the build tool is replaced by a few lines of Java.

Modules you already use

Every class belongs to a module. Code on the classical class path, like the code in our editor, belongs to the unnamed module. JDK classes belong to named modules such as java.base (always present: java.lang, java.util, java.io, ...), java.sql, java.net.http and java.logging. You can ask the runtime about them:

Java Exploring the modules of the running JVM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The java.sql descriptor is a good model of a real module: it requires a few modules (requires transitive means "and my users get them too," explained below), exports its API packages, and uses a service (java.sql.Driver, so JDBC drivers can plug in). java.base exports java.util but not its internal jdk.internal.* packages, and it doesn't open java.lang to reflection, which is why the reflection lesson couldn't setAccessible a String's private field. (The mandated modifier means a module always requires java.base implicitly.)

The module descriptor

A module lives in a folder whose root contains module-info.java. A typical project layout with two modules:

TEXT
src/
โ”œโ”€โ”€ com.shop.pricing/
โ”‚   โ”œโ”€โ”€ module-info.java
โ”‚   โ””โ”€โ”€ com/shop/pricing/
โ”‚       โ”œโ”€โ”€ api/Prices.java            โ† exported: other modules may use it
โ”‚       โ””โ”€โ”€ internal/TaxTable.java     โ† not exported: hidden, even though it's public
โ””โ”€โ”€ com.shop.app/
    โ”œโ”€โ”€ module-info.java
    โ””โ”€โ”€ com/shop/app/App.java
Java
// src/com.shop.pricing/module-info.java
module com.shop.pricing {
    exports com.shop.pricing.api;
}

// src/com.shop.app/module-info.java
module com.shop.app {
    requires com.shop.pricing;
}

Module names follow the reverse-domain convention of packages, and the usual choice is the name of the module's main package. The directives you'll use:

Directive Meaning
requires M; This module reads module M and can use its exported packages
requires transitive M; ...and any module that requires this module also reads M (use it when M's types appear in your API)
requires static M; Needed at compile time, optional at run time (for optional integrations, annotation libraries)
exports p; Public types in package p are accessible to all modules that read this one
exports p to M1, M2; A qualified export: only the named modules get access
opens p; / opens p to M; Allows deep reflection (private members, setAccessible) on package p at run time
open module M { ... } Opens every package of the module
uses S; This module looks up implementations of service type S with ServiceLoader
provides S with Impl; This module supplies Impl as an implementation of service S

Accessibility now has two levels. A type is usable from another module only if it is public and its package is exported to that module and the other module requires this one. That combination is called strong encapsulation.

Strong encapsulation in action

The next example builds the two modules above, runs them, and then tries to break the rules in two ways: by compiling code that imports the internal package, and by reaching it with reflection at run time.

Java Two real modules and strong encapsulation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 1 succeeds because Prices lives in the exported api package and com.shop.app requires the module. Step 3 shows run-time enforcement: even though TaxTable and apply are both public, reflection from outside the module throws IllegalAccessException, because the package isn't exported. Step 4 shows compile-time enforcement: from inside com.shop.app, the non-exported package simply "does not exist," so javac rejects the import. (When the package is visible but not exported to your module, javac's message is "package ... is not visible" instead.) The library author can now rename, rewrite or delete TaxTable freely.

Modules also prevent split packages: two modules may not contain the same package. And they fail fast. If a required module is missing, the JVM refuses to start, with a clear "module not found" error, instead of throwing NoClassDefFoundError an hour later, as happens on the class path.

exports vs opens: reflection on your own classes

exports gives compile-time and run-time access to public members. It does not allow deep reflection on private ones. Frameworks like Jackson, Hibernate and Spring need exactly that deep access to read and write your private fields, so you opens the package that holds those classes, ideally only to the framework module:

Java
module com.shop.app {
    requires com.fasterxml.jackson.databind;
    exports com.shop.app.api;
    opens com.shop.app.model to com.fasterxml.jackson.databind, org.hibernate.orm.core;
}

opens without exports is common: the framework may reflect on your entities at run time, but no other module can compile against them. This example compares an exported package with an opened one:

Java exports allows public access, opens allows deep reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The results show the difference: both packages allow reflective calls to public members at run time, but only the opened package allows setAccessible on the private field. The exported package, in turn, is the only one other modules can compile against: import com.shop.data.model.Customer; in another module would fail, because opens grants run-time reflective access only. In practice, open only what frameworks truly need, and qualify it with to so other modules don't get the same privilege.

Services: ServiceLoader with modules

Modules have a built-in plugin mechanism. An API module declares an interface; any number of provider modules declare provides Interface with Implementation;; a consumer declares uses Interface; and asks ServiceLoader for whatever implementations are present. The consumer never names an implementation class, and providers don't even need to export their packages.

Java Plugging in implementations with provides and uses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Only com.notify.api was requested, yet both provider modules end up in the layer: resolveAndBind (what the java launcher does) adds every observable module that provides a service some resolved module uses. In a normal modular application, the consumer code is simply:

Java
for (Notifier notifier : ServiceLoader.load(Notifier.class)) {
    notifier.send("Sam", "your order shipped");
}

Drop another provider JAR on the module path and it shows up, no code changes needed. The JDK uses this for JDBC drivers, charsets, java.net.http and many tools. (Our example calls the methods reflectively only because Main itself sits outside the new layer and can't name the Notifier type at compile time.)

The module path, the class path and migration

Modules come from the module path (--module-path or -p), alongside the old class path:

Terminal
javac -d out --module-source-path src -m com.shop.app           # compile modules
java  -p out -m com.shop.app/com.shop.app.App                    # run module/main-class
jar   --create --file shop-app.jar --main-class com.shop.app.App -C out/com.shop.app .
java  -p libs:shop-app.jar -m com.shop.app                       # run from modular JARs

The ecosystem moved to modules gradually, so the JVM bridges the two worlds:

Kind What it is Reads Exports/opens
Named module A JAR with module-info.class on the module path Only what it requires Only what it declares
Automatic module A plain JAR placed on the module path; its name comes from the Automatic-Module-Name manifest entry or the file name Every other module All its packages
Unnamed module Everything on the class path Every module All its packages (but named modules can't requires it)

That's why you can migrate bottom-up or top-down, and why most applications still run happily on the class path: everything there is in the unnamed module, and the JDK's own modules are still encapsulated from it. Whether your application should become modular depends on the payoff. Libraries benefit most (a clean, enforced API), as do applications that want a small jlink runtime. Many Spring Boot applications stay on the class path, and that is a perfectly valid choice.

Tools that help: jdeps --print-module-deps app.jar lists the JDK modules a JAR really uses, and jdeps --jdk-internals finds uses of encapsulated internals that will break.

Because the JDK is modular, jlink can assemble a Java runtime that contains only the modules your application needs, plus your own modules:

Terminal
jlink --module-path out --add-modules com.shop.app \
      --strip-debug --no-header-files --no-man-pages --compress zip-6 \
      --launcher shop=com.shop.app/com.shop.app.App \
      --output shop-runtime

./shop-runtime/bin/shop               # runs without any installed JDK
./shop-runtime/bin/java --list-modules

A runtime with only java.base is roughly 50 MB uncompressed instead of about 300 MB for a full JDK, which makes container images smaller and startup a little faster. jlink needs named modules (automatic modules aren't allowed), which is one practical reason applications modularize. For a non-modular app, you can still build a slim runtime from the JDK modules it uses: jlink --add-modules $(jdeps --print-module-deps app.jar) .... Since JDK 24, jlink can also work without the separate jmods folder, so some JDK builds no longer ship it.

Modules vs packages, at a glance

Package Module
Groups Classes Packages
Declared by package statement in each file module-info.java at the module root
Controls access with public, protected, package-private, private exports, opens (on top of the modifiers)
Dependencies Implicit (whatever is on the class path) Explicit requires, checked at startup
Enforced Compile time and run time (for members) Compile time and run time, including reflection
Since Java 1.0 Java 9

Don't confuse modules with import module java.base;, the module import declaration of Java 25: it's just a shortcut that imports all packages a module exports (see Packages and Imports). It works in any code, modular or not, and is what makes compact source files see List and Map without imports.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Module com.lib contains a public class in package com.lib.internal, which is not exported. Code in module com.app (which requires com.lib) imports that class. What happens?

    Strong encapsulation applies at compile time too. A public type is only accessible to other modules if its package is exported.
  2. 2. Jackson must read private fields of classes in your package com.app.model, and no other module should compile against them. Which directive fits best?

    opens allows deep reflection at run time without exporting the package for compilation, and the qualified form limits it to the framework module.
  3. 3. Module A has requires transitive B;. Module C has requires A;. Which modules can C read?

    requires transitive passes readability on, so any module requiring A also reads B. java.base is always read implicitly.
  4. 4. Where does code loaded from the classic class path live?

    Every class belongs to a module. Class-path code is in the unnamed module, which reads every module but cannot be required by named modules.
  5. 5. A consumer module declares uses com.pay.Gateway; and calls ServiceLoader.load(Gateway.class). How do implementations become available?

    Providers announce themselves with provides ... with. The consumer never names them, and the providers don't need to export their implementation packages.

Summary

  • A module is a named set of packages described by module-info.java. Every class is in a module; class-path code is in the unnamed module.
  • requires declares dependencies (transitive passes them on, static makes them compile-time only); exports makes packages usable by other modules, optionally only to specific ones.
  • Strong encapsulation: public types in non-exported packages are inaccessible from other modules, at compile time and at run time, even by reflection.
  • opens (or open module) allows deep reflection for frameworks; prefer qualified opens ... to.
  • Services decouple modules: uses in the consumer, provides ... with in providers, ServiceLoader to find them.
  • Modules give reliable configuration (missing modules fail at startup, no split packages); automatic modules and the unnamed module make gradual migration possible.
  • jlink builds a custom runtime with only the needed modules; jdeps shows what you depend on.

Next: Object-Oriented Design Principles (SOLID), where you'll learn five principles that keep classes and modules easy to change.