Lesson · Modules & Service Loading
Java Platform Module System
12 min readJava Platform Module System
The class path is a list of places to look. The module path is a declaration the platform resolves before main runs, and it fails loudly when the declaration cannot be kept. This lesson is about the layer above packages: module-info.java, the directives, resolution, and the unnamed and automatic modules that carry a codebase through migration.
What the class path could not promise
The class path is a flat list of places to look. Anything on it can see everything else on it, position decides which copy of a class wins, and nothing is checked until the class is first needed. That carried the platform for two decades, and it produces a family of failures you have probably debugged already.
None of the four failures below is a mistake in application code. They are properties of a lookup list that carries no information about who needs what.
- No reliable configuration: a missing jar is not noticed at startup. The first reference to one of its classes fails with
NoClassDefFoundError, sometimes hours into a run. - No version discipline: two jars with the same classes can sit on the class path and the first one found wins silently. Nothing tells you the second was ignored.
- Split packages: two jars can each contribute classes to one package, so the package stops being a unit and its package-private internals leak across jars that never agreed to share.
- JDK internals open by default: before JDK 9, reflection could reach any internal type with
setAccessible(true), so every JDK package was effectively public and every implementation detail was a potential dependency.
The class path answers where to look; it never answers who depends on what. JPMS exists to make the second answer explicit, and to check it before the application starts.
module-info.java: the declaration the platform reads first
A module is a jar or a directory with a module-info.class at its top level. The source file that produces it, module-info.java, sits at the root of the source tree and declares three things: the module's name, what it needs, and what it offers. It is compiled like any other source file, and the platform reads it during resolution, before main runs.
Six directives cover the whole surface. Four control visibility, two control services, and each has one job.
| Directive | What it does | The form you will also meet |
|---|---|---|
requires M | this module reads M at compile time and at run time | requires transitive M: every reader of this module also reads M |
requires static M | M is needed to compile and optional at run time; resolution does not search for it | used for annotations and optional integrations |
exports p | other modules may compile against package p and use its public types | exports p to M narrows the reader to one module |
opens p | deep reflection on p is allowed, so setAccessible can reach non-public members | opens p to M narrows the reader; this is what --add-opens imitates |
uses S | this module looks up providers of service S at run time | the consumer side of the next lesson |
provides S with I | this module offers I as an implementation of S | the provider side; the package does not need to be exported |
- requires transitive is about your readers, not about you. If a module exposes types from N in its own API, it should require transitive N, so callers read N without ever naming it.
- exports and opens are different doors. exports is for the compiler and the linker. opens is only for reflection. A package can be exported and not opened, opened and not exported, both, or neither.
- A provider package should not be exported.
provides ... with ...is enough for the platform to instantiate the implementation, and keeping the package closed hides it from callers.
The descriptor is a contract with the startup sequence, not a build file. Everything it declares is checked before your code runs, which is why a missing module is a launch error with a name in it rather than a surprise later.
Module graph · what requires, exports and opens draw
structure only; resolution order is the play area's job
opens is a door, exports is a window. The internal package is closed to the compiler but reachable by reflection for one named reader, which is the difference between a compile error and an InaccessibleObjectException.
Every arrow exists because a descriptor says so. That is the whole difference from the class path, where the same picture would be implied by nothing and checked by nobody.
Module path and class path: two lanes, two philosophies
The module path is where resolved modules live. Each entry is a modular jar, an exploded module, or a jar that becomes an automatic module. Entries are found by module name rather than by position, and the platform refuses two modules with the same name.
The class path is unchanged: jars and directories searched in order, first match wins, no names attached. The difference that matters is not where the bytes are, it is what gets checked and when.
| Module path | Class path | |
|---|---|---|
| how a class is found | inside the module that exports its package | the first entry in the list that has it |
| duplicate modules | refused: the error names both jars | silently ignored |
| duplicate packages | refused when two modules export the package to one reader | allowed: the first copy of each class wins |
| who can see a package | only modules that read it, and only if it is exported | everything on the class path |
| when problems appear | at launch, before main | at the first use of whatever is missing |
The module path is a declaration you must keep; the class path is a promise nobody checks. Every jar you place chooses which of the two you are relying on.
The unnamed module and the automatic module
Code on the class path has no descriptor to read, so the platform cannot leave it out of the module system. Each class loader gets one unnamed module that holds everything it loads from the class path, and that module behaves the way the class path always did: it reads every named module, it exports all of its packages to everyone, and all of its packages are open, so setAccessible succeeds against it.
The reverse does not hold. A named module needs an explicit read to see the unnamed module, which is what --add-reads com.acme.core=ALL-UNNAMED adds. That asymmetry is the everyday fact behind framework code on the class path being able to call your modular code while your modular code cannot call back. The reflection-encapsulation lesson takes the same asymmetry from the caller's side, where it shows up as --add-opens.
A jar with no descriptor placed on the module path is not rejected either. It becomes an automatic module: a named module whose name is derived from the file, which exports every package and reads every module in the graph.
| Named module | Automatic module | Unnamed module | |
|---|---|---|---|
| descriptor | module-info.class | none: the module is derived from the jar | none |
| name | declared in the descriptor | from the file name, or Automatic-Module-Name | none; getModule().isNamed() is false |
| exports | only what it declares | every package | everything, to every module |
| reads | only what it requires | everything enumerated in the graph | every named module |
| where it comes from | the modules you write | dependency jars moved to the module path | everything left on the class path |
- The derived name is the file name, cleaned up. The
.jarsuffix goes, a trailing version is dropped, and every non-alphanumeric character becomes a dot, soacme-util-2.4.1.jarbecomes moduleacme.util. AnAutomatic-Module-Nameentry in the manifest takes precedence, and every library should set one so its name stops depending on its file name. - Both are migration devices, not destinations. The unnamed module keeps existing code running; the automatic module lets one jar at a time move to the module path. Neither gives you the checking or the encapsulation the module path was adopted for.
Automatic and unnamed modules are how a codebase moves, not what it should end up as. Their purpose is to make the migration incremental.
Resolution at startup: from roots to a graph
Before main runs, the launcher resolves modules. It starts from a set of root modules, usually the one named on the command line plus anything from --add-modules, then follows requires edges outward, and finally validates the readability graph that comes out.
The algorithm has two steps and a short list of ways to fail, and each failure names the module it is about.
| Message | What it means | When you see it |
|---|---|---|
FindException: Module com.acme.json not found, required by com.acme.core | a requires edge points at a module that nothing on the module path provides | at launch, during resolution |
error: package com.acme.util is declared in module acme.util, which does not export it to module com.acme.core | the package exists in a resolved module but is not exported to the reader | at compile time, in javac |
module com.acme.core reads package com.acme.util.text from both acme.util and legacy.util | two modules export the same package to one reader: a split package | at compile time in javac, and in the same shape at launch when the graph is refused |
InaccessibleObjectException from setAccessible | the package is exported but not opened, so deep reflection is refused | at run time, on the caller's side |
- Collect the roots: the module named on the command line (
--module com.acme.app/com.acme.app.Main) plus every module listed with--add-modules. - Enumerate dependencies: follow every
requiresand everyrequires transitiveedge outward.requires staticedges are not searched, though the edge counts if that module is enumerated for another reason. - If the graph contains any automatic module, enumerate every observable automatic module, because an automatic module reads everything and would otherwise leave edges unaccounted for.
- Compute the readability graph and validate it: no two modules may export the same package to a module that reads both, and no module may read two modules with the same name.
- Either fail with a message that names the module and the reason, or start the application.
Resolution is a startup check, and that is the point. A missing module or a split package becomes a failed launch that names the culprit, instead of a NoClassDefFoundError on some request hours later.
Startup resolution · roots, requires edges, one graph
A launch with only a module path: java --module-path mods --module com.acme.app/com.acme.app.Main. The launcher takes com.acme.app as its single root module and starts looking for descriptors instead of for class files.
Module and jar names are illustrative. The rules they demonstrate are the platform's: requires edges are resolved before main, a package may have one owner per reader, and everything on the class path lands in the unnamed module.
Migrating without a rewrite
Nobody moves a running application to the module path in one step. The order that holds up is bottom-up and incremental, and the tooling tells you where to start.
- Run on the class path first and treat that as a valid destination, not a failure. Since JDK 9 the JDK itself is modular, so class path code already sees modules below it and keeps working.
- Ask the tooling what the code actually needs.
jdeps --jdk-internalslists uses of JDK internals that no longer resolve, andjdeps --generate-module-infodrafts amodule-info.javaper jar from the real references. - Modularise bottom-up, starting with the jars nothing else in the build depends on. Each step is one descriptor, and everything not yet moved stays on the class path.
- Fix graph errors as they appear: a
FindExceptionnames the missing module, a split package names both modules and the shared package, and a non-exported package names the module that declares it. - Bridge the rest deliberately.
--add-opens,--add-exportsand--add-readsopen one package or one edge for one launch, and each belongs in a comment next to the dependency that needed it.
- Split packages are the usual blocker. If two of your own jars share a package, one of them has to move, be merged, or be patched with
--patch-modulewhile you do the real fix. - The bridges are launch flags, not architecture. The reflection-encapsulation lesson treats each one as a permanent hole in a boundary; name the dependency that needs it and the plan for removing it.
- Service loading is often the quiet part. A modularised consumer stops discovering providers the class path used to expose until it declares
uses, which is the subject of the next lesson.
Migrate for a reason, not for fashion. Strong encapsulation of your own internals, a dependency graph the launcher validates, and jlink images are the payoffs; a single-jar application with no public API gains very little.
What you actually get
The first payoff is checking. Every requires in the graph resolves before startup, every exported package is a decision someone wrote down, and an accidental dependency on a JDK internal fails instead of working until the next upgrade.
The second is that the JDK itself is modular, and that is what makes the tooling possible: jdeps can map a jar's references onto module names, and jlink can assemble a runtime image from exactly the modules an application needs, without the rest of the JDK. The packaging and deployment lesson takes image building from there.
- Strong encapsulation for your own jars too: a package that is not exported is unreachable, which stops accidental coupling between modules the way private stops it inside a class.
- A named dependency graph: jdeps can print it, the launcher validates it, and jlink can act on it.
- A smaller runtime: a jlink image contains the application's modules and their transitive dependencies, not a full JDK.
The module path is a declaration you must keep; the class path is a promise nobody checks. Decide where each jar sits knowing which one you are choosing.
The jar that worked on the class path
Two jars share a package, often because one vendored or relocated the other. On the class path that is invisible: the first copy of each class wins and nobody is told. Move both jars to the module path and the overlap becomes a split package, refused by resolution because a module reads that package from both sources, and the message names both modules. The same move can also surface later as a NoClassDefFoundError, when the class you relied on was never in the readability graph at all, because on the module path visibility comes from requires rather than from position. Merge the packages, drop the duplicate jar, or keep one of them on the class path while you untangle the dependency.
Interview angles
What does the module system give you that the class path did not?+
A declared dependency graph that is resolved before the application starts, and strong encapsulation: a package is visible only if it is exported, and only to modules that read it. Both are checked, so a missing dependency is a failed launch that names the module.
The checking is what changes the failure mode. On the class path, a missing jar is discovered by whichever request first needs one of its classes; on the module path, resolution walks the requires edges first and refuses to start.
exports versus opens?+
exports is compile-time and link-time access to the public types of a package. opens is permission for deep reflection, so setAccessible can reach non-public members. A package can be exported and not opened, opened and not exported, both, or neither.
Follow-up: What changes for class path code, which lives in the unnamed module? Every package of the unnamed module is open to all modules, which is why the same reflective call works from a jar on the class path and fails inside a modular application.
What is an automatic module, and where does its name come from?+
A jar without module-info on the module path. It exports every package and reads every module in the graph. Its name is derived from the file name: the .jar suffix and a trailing version are dropped and non-alphanumeric characters become dots, so acme-util-2.4.1.jar becomes acme.util.
Common misconception: That an automatic module is a safe long-term state. It exposes every package, including internals you never meant to publish, so it is a step on the way to a descriptor rather than a destination.
A jar works on the class path and fails on the module path. Where do you look?+
First at the graph: a FindException names the module a requires edge could not find, and a split package names both modules that export the same package to one reader. Then at visibility: a type in a resolved module whose package is not exported to the reader fails to compile, and a package that is exported but not opened refuses setAccessible.
The two families are different problems. Resolution failures happen before any of your code runs, so they are about module identity and edges. Access failures happen during compilation or reflection, so they are about exports and opens.
What does requires transitive change?+
It propagates readability. Every module that reads the declaring module also reads the required one, so a module can expose types from its own dependencies in its API without callers naming those dependencies. It is the module equivalent of a public method signature mentioning another type.
Without it, callers that use those exposed types have to add their own requires for a module they never mentioned, which is exactly the leak that makes a dependency part of your API without anyone deciding it is.