Java Modules: module-info, requires, exports and opens
A module in Java is a named set of packages described by a module-info.java file. In that descriptor the module itself states which modules it needs (requires), which packages it makes available to others for normal use (exports) and which ones for reflection (opens). Everything else is hidden, even public classes. The module system is called JPMS (Java Platform Module System) and arrived in Java 9.
// module-info.java of the module com.shop.catalog
module com.shop.catalog {
exports com.shop.catalog.api; // other modules can see this package
} // com.shop.catalog.internal stays hidden Below: how module-info.java is structured, how requires, requires transitive and requires static differ, when you need exports and when opens, and which errors javac and java report. All examples form a small "shop" made of several modules and were checked on JDK 25.
1. What a module is and why JPMS exists
Before Java 9 a program was a set of JAR files on the class path. That approach has three well-known problems:
- No encapsulation between JAR files. Every
publicclass is available to everyone, so other code freely uses a library's internal classes, and the library author cannot change them. - Dependencies are not checked at startup. If a required JAR is missing, the program starts and fails with
NoClassDefFoundErroronly when it reaches the missing class. - One package in two JARs. If the same classes sit in two JAR files, the one earlier on the class path wins, without any warning.
JPMS solves all three: a module lists its dependencies and exported packages explicitly, the JVM checks the module graph at startup, and a package can belong to only one of the modules that a given module reads. The JDK itself is split into modules too: java.base, java.sql, java.logging and about seventy more (the java --list-modules command prints the list).
The word "module" means different things in Java, and they are often confused:
| Concept | What it is | Described by |
|---|---|---|
| Package | A namespace for classes | package com.shop.catalog.api; |
| JPMS module | A set of packages with explicit dependencies and access rules | module-info.java |
| JAR file | An archive of classes; a modular JAR contains module-info.class | MANIFEST.MF, module-info.class |
| Maven module | A part of the project build with its own pom.xml | pom.xml (see Maven multi-module project) |
Maven modules and JPMS modules are independent: a multi-module Maven project may have no module-info.java at all, or one in every Maven module.
2. The module-info.java file: location, name, directives
The module descriptor is a file with the fixed name module-info.java in the root of the module's sources, next to the package directories, not inside them. The source directory is usually named after the module:
src/
├── com.shop.catalog/
│ ├── module-info.java
│ └── com/shop/catalog/
│ ├── api/Catalog.java
│ └── internal/PriceRules.java
└── com.shop.app/
├── module-info.java
└── com/shop/app/Main.java The compiler turns it into module-info.class. A module name follows the same rules as a package name: identifiers separated by dots, usually in reverse-domain style (com.shop.catalog). Hyphens, keywords and parts that start with a digit are not allowed. The module name does not have to match a package name, but matching the main package is good practice.
Inside the braces are directives. Their order does not matter:
| Directive | Meaning |
|---|---|
requires M; | The module needs module M at compile time and at run time |
requires transitive M; | The same, plus every module that reads this module automatically reads M too |
requires static M; | M is mandatory at compile time and optional at run time |
exports P; | The public types of package P are available to all modules |
exports P to M1, M2; | Package P is exported only to the listed modules (qualified export) |
opens P; / opens P to M; | Package P is open to deep reflection at run time |
open module M { } | All packages of the module are open to reflection |
uses / provides ... with | Services and ServiceLoader, covered in a separate lesson of this module |
3. A first modular program: compiling and running
The module com.shop.catalog exports the api package and hides the internal package:
// src/com.shop.catalog/module-info.java
module com.shop.catalog {
exports com.shop.catalog.api;
}
// src/com.shop.catalog/com/shop/catalog/api/Catalog.java
package com.shop.catalog.api;
import com.shop.catalog.internal.PriceRules;
public class Catalog {
public String find(String id) {
return id + ": " + PriceRules.price(id);
}
}
// src/com.shop.catalog/com/shop/catalog/internal/PriceRules.java
package com.shop.catalog.internal;
public class PriceRules {
public static int price(String id) { return id.length() * 100; }
} The module com.shop.app uses it:
// src/com.shop.app/module-info.java
module com.shop.app {
requires com.shop.catalog;
}
// src/com.shop.app/com/shop/app/Main.java
package com.shop.app;
import com.shop.catalog.api.Catalog;
public class Main {
public static void main(String[] args) {
Catalog catalog = new Catalog();
System.out.println(catalog.find("book"));
System.out.println(Main.class.getModule().getName());
System.out.println(Catalog.class.getModule().getName());
}
} Both modules are compiled with one command and run from the module path (-p) instead of the class path:
javac -d out --module-source-path src -m com.shop.app,com.shop.catalog
java -p out -m com.shop.app/com.shop.app.Main
book: 400
com.shop.app
com.shop.catalog --module-source-path src tells the compiler that src contains module directories, -p out says where to find compiled modules, and -m module/class names the module and main class to run. The javac and java options are covered in detail in this module's lesson on compiling and running.
4. requires: which modules a module reads
The requires directive creates a "module reads module" relation (readability). Code in a module can use types of another module only if it reads that module. Without requires com.shop.catalog, the module com.shop.app does not compile:
error: package com.shop.catalog.api is not visible
(package com.shop.catalog.api is declared in module com.shop.catalog, but module com.shop.app does not read it) The rule applies to JDK modules as well. An empty module sees only java.base: every module reads it implicitly, so java.util.List, java.time.LocalDate or java.nio.file.Path are available without requires. But java.sql.Connection lives in the java.sql module:
module m.x { } // no requires java.sql
// p/x/A.java
public class A {
java.sql.Connection c; // error
java.util.List<String> l; // compiles: java.base
}
// error: package java.sql is not visible
// (package java.sql is declared in module java.sql, but module m.x does not read it) Modules are checked in two places:
- At compile time:
requires com.shop.payments;with no such module giveserror: module not found: com.shop.payments. - At startup: if a module was deleted after compilation, the JVM does not start at all, even if the code would never reach it:
java -p out -m com.shop.app/com.shop.app.Main
Error occurred during initialization of boot layer
java.lang.module.FindException: Module com.shop.catalog not found, required by com.shop.app One more rule: cycles are forbidden. If m.a requires m.b and m.b requires m.a, the compiler reports cyclic dependence involving m.a. Even requires m.x; inside m.x itself is a cycle.
5. exports: which packages are visible outside
Reading a module is not enough: another module sees only the packages listed in exports. Using a hidden package does not compile, even with requires:
// in module com.shop.app
import com.shop.catalog.internal.PriceRules;
// error: package com.shop.catalog.internal is not visible
// (package com.shop.catalog.internal is declared in module com.shop.catalog, which does not export it) This gives Java a new access level on top of the modifiers: a public class is accessible from another module only if its package is exported and the other module reads this module. Inside a module the usual rules apply; see Access Modifiers in Java.
| Condition | Access to a public class from another module |
|---|---|
No requires, package exported | No: does not read it |
requires present, package not exported | No: which does not export it |
requires present, package exported | Yes |
Important details of exports:
- You export a package, not a class.
exports com.shop.catalog.api.Catalog;orexports com.shop.*;are not allowed. - Subpackages are not exported with the package.
com.shop.catalogandcom.shop.catalog.apiare different packages, each exported separately. Exporting an empty or missing package is the errorpackage is empty or does not exist. - Only
publicandprotectedmembers of an exported package are visible, as before. Package-private classes andprivatefields stay closed.
A qualified export opens a package not to everyone but only to the listed modules, for example to plugins:
module com.shop.core {
exports com.shop.core.api;
exports com.shop.core.spi to com.shop.plugins;
}
// in com.shop.plugins: com.shop.core.spi.Hook is accessible
// in com.shop.app:
// error: package com.shop.core.spi is not visible
// (package com.shop.core.spi is declared in module com.shop.core, which does not export it to module com.shop.app) If a module in the to list does not exist, it is not an error, only the warning [module] module not found: the target module may appear later.
6. requires transitive: passing a dependency on
Readability is not transitive. Suppose com.shop.catalog returns the record Product from the module com.shop.model:
module com.shop.model {
exports com.shop.model; // record Product(String id, int price)
}
module com.shop.catalog {
requires com.shop.model;
exports com.shop.catalog.api; // public Product find(String id)
}
module com.shop.app {
requires com.shop.catalog;
}
// in com.shop.app
import com.shop.model.Product;
Product p = new Catalog().find("book");
// error: package com.shop.model is not visible
// (package com.shop.model is declared in module com.shop.model, but module com.shop.app does not read it) com.shop.app reads com.shop.catalog but not com.shop.model, so it cannot name the type it receives from the method. There are two fixes: add requires com.shop.model; to com.shop.app, or, better, make the dependency transitive in the module that exposes the type:
module com.shop.catalog {
requires transitive com.shop.model;
exports com.shop.catalog.api;
}
// now com.shop.app compiles and prints:
// Product[id=book, price=400] The rule: if a type from module M appears in the public API of your exported package (return type, parameter, superclass), write requires transitive M. The compiler suggests it with the -Xlint:exports flag:
warning: [exports] record Product in module com.shop.model is not indirectly exported using 'requires transitive' JDK modules work the same way. The java.sql module returns types from java.logging and java.xml, so it requires them transitively:
java --describe-module java.sql
java.sql@25.0.3
exports java.sql
exports javax.sql
requires java.logging transitive
requires java.transaction.xa transitive
requires java.base mandated
requires java.xml transitive
uses java.sql.Driver 7. requires static: a compile-time-only dependency
requires static means the module is mandatory at compile time but may be absent at run time. This is how optional features are wired in: annotations for tools, metrics, integrations:
module com.shop.app {
requires static com.shop.metrics;
}
public class Main {
public static void main(String[] args) {
boolean present = ModuleLayer.boot().findModule("com.shop.metrics").isPresent();
System.out.println("metrics present: " + present);
if (present) {
com.shop.metrics.Metrics.count("start");
}
}
} java -p out -m com.shop.app/com.shop.app.Main
metrics present: false
java -p out --add-modules com.shop.metrics -m com.shop.app/com.shop.app.Main
metrics present: true
metric: start Look at the first run: the com.shop.metrics module is in out but is not loaded, because nobody requires it with a plain requires. The --add-modules option adds it to the graph. If you call Metrics.count() without the check and the module is absent, the program starts and fails at that call with NoClassDefFoundError: com/shop/metrics/Metrics. The combination requires transitive static is also allowed.
8. opens and open module: access for reflection
exports grants normal access to public members. But frameworks (Hibernate, Jackson, Spring) also read private fields through reflection with setAccessible(true). That is deep reflection (reflection itself is covered in Java Reflection API: the Class Object), and it needs opens:
// module com.shop.model: exports com.shop.model; (no opens)
public class Order {
private String status = "NEW";
}
// module com.shop.json (requires com.shop.model)
Object order = new com.shop.model.Order();
Field f = order.getClass().getDeclaredField("status");
f.setAccessible(true);
System.out.println("status = " + f.get(order));
// InaccessibleObjectException: Unable to make field private java.lang.String com.shop.model.Order.status
// accessible: module com.shop.model does not "opens com.shop.model" to module com.shop.json After opens com.shop.model; the same code prints status = NEW. How the directives differ:
| Directive for the package | Code in another module compiles | Reflection on public | setAccessible(true) on private |
|---|---|---|---|
| None | No | No | No |
exports | Yes | Yes | No, InaccessibleObjectException |
opens | No: is not visible | Yes | Yes |
exports + opens | Yes | Yes | Yes |
The key point: opens works only at run time. If a package is opened but not exported, plain code like new com.shop.model.Order() in another module does not compile.
Variants of opens:
opens P to M;opens the package to moduleMonly. If you open it, say,to java.logging, the modulecom.shop.jsongetsInaccessibleObjectExceptionagain.open module M { ... }opens all packages of the module to reflection. Inside such a module theopensdirective is not allowed ('opens' only allowed in strong modules), andexportsis still needed for normal access.--add-opensis a launcher option that opens a package without editingmodule-info:java --add-opens com.shop.model/com.shop.model=com.shop.json .... It is used for modules you do not own, including JDK modules.
JDK modules are closed to deep reflection even from class-path code. Trying to reach the private field String.value throws InaccessibleObjectException, and with --add-opens java.base/java.lang=ALL-UNNAMED it works (ALL-UNNAMED means all code on the class path).
9. Inspecting a module: --describe-module
The java --describe-module command (short form -d) shows what a module requires, exports and opens. For a module declared like this:
module com.shop.catalog {
requires transitive com.shop.model;
exports com.shop.catalog.api;
} java -p out --describe-module com.shop.catalog
com.shop.catalog file:///.../out/com.shop.catalog/
exports com.shop.catalog.api
requires com.shop.model transitive
requires java.base mandated How to read the output:
- The modifier comes after the name:
requires com.shop.model transitive, notrequires transitive com.shop.model. requires java.base mandatedappears for every module, even if itsmodule-infosays nothing aboutjava.base.- Non-exported packages are printed as
contains, for examplecontains com.shop.catalog.internal; exports to specific modules appear asqualified exports ... to .... - For an open module, the first line ends with the word
openafter the path.
10. Does module-info compile? Typical errors
The module contains one package p.x with one public class. Results were obtained on JDK 25:
| module-info.java | Result |
|---|---|
module m.x { exports p.x; exports p.x; } | Error: duplicate or conflicting exports |
module m.x { requires java.sql; requires java.sql; } | Error: duplicate requires |
module m.x { exports p.none; } | Error: package is empty or does not exist |
module m.x { exports p; } | Error: package p is empty, the subpackage p.x does not count |
module m.x { exports p.x.*; } | Error: wildcards are not supported |
module m.x { requires m.x; } | Error: cyclic dependence |
open module m.x { opens p.x; } | Error: 'opens' only allowed in strong modules |
module m.x { opens p.x; exports p.x; } | Compiles |
module m.x { requires transitive static java.sql; } | Compiles |
module m.x { requires java.base; } | Compiles: allowed, but not needed |
module m.x { exports p.x to some.missing; } | Compiles with the warning module not found |
module my-app { }, module com.2app { }, module com.int.app { } | Errors: a hyphen, a part starting with a digit, a keyword |
module my_app { }, module transitive { } | Compile: transitive is a contextual keyword, not a reserved one |
A separate error is the split package. If two modules export the same package, a module that reads both does not compile, even when they contain different classes:
module com.shop.a { exports com.shop.util; } // class A
module com.shop.b { exports com.shop.util; } // class B
module com.shop.app {
requires com.shop.a;
requires com.shop.b;
}
// error: module com.shop.app reads package com.shop.util from both com.shop.a and com.shop.b 11. Code without module-info: the unnamed module
Modules are optional. If you run the same classes from the class path, the program works as before:
java -cp "out/com.shop.app;out/com.shop.catalog" com.shop.app.Main
book: 400
null
null The class-path separator is ; on Windows and : on Linux and macOS. Here getModule().getName() returns null: all class-path code goes into the unnamed module, and module-info.class is ignored. The unnamed module reads all modules and exports all its packages, so JPMS checks do not apply to it. How to move such a project to modules step by step, through automatic modules, is the topic of a separate lesson in this module.
Frequently asked questions
Do I have to write module-info.java in my project?
No. Without it, code runs on the class path, inside the unnamed module, as before Java 9. Modules are worth it when you need strong encapsulation of a library, dependency checks at startup, or a trimmed runtime image built with jlink. Many Spring applications still work without module-info.java.
What is the difference between exports and opens?
exports gives access to the package's public types at compile time and at run time. opens allows only deep reflection at run time, including setAccessible(true) on private fields, and plain code using such a package does not compile. Frameworks like Hibernate or Jackson usually need opens; your own code needs exports.
When do I need requires transitive?
When a type from a dependency is visible in your module's public API, for example a method of an exported class returns it. Then everyone who reads your module needs that type too, and requires transitive saves them an extra requires. If the dependency is used only inside the implementation, a plain requires is enough.
Why is a public class not accessible from another module?
Because its package is not exported, or your module does not read the module that contains the class. The javac message tells you which: which does not export it means no exports, does not read it means no requires. In the module system, public means "available to everyone the module allows", not "available to everyone".
Do I need to write requires java.base?
No. The java.base module (packages java.lang, java.util, java.io, java.time and others) is read implicitly by every module; in --describe-module output this is the line requires java.base mandated. An explicit directive is allowed and changes nothing. Other JDK modules, such as java.sql or java.net.http, must be required explicitly.
Comments