module-info in Java: Every Module Directive Explained
module-info in Java is the file module-info.java that declares a module: its name, the modules it depends on, the packages it shares, the packages it opens for reflection, and the services it uses or provides. The compiler turns it into module-info.class, and both javac and the JVM enforce every line of it.
The previous lesson, Java Modules, used only requires and exports. This lesson covers the full module descriptor: requires transitive, requires static, qualified exports ... to, opens and open module for reflection, and uses / provides ... with for plugin-style services. Every directive comes with a runnable multi-module example and its real output.
module-info in Java: Syntax and Rules
A module declaration has a name and a body of directives. It sits at the root of the module's source folder, next to the top-level package folders.
[open] module module.name {
requires [transitive | static] other.module;
exports package.name [to module.a, module.b];
opens package.name [to module.a, module.b];
uses service.Interface;
provides service.Interface with implementation.Class [, another.Class];
}
| Directive | Purpose |
|---|---|
requires M | This module reads module M (needs it to compile and run) |
requires transitive M | This module reads M, and every module that reads this one also reads M |
requires static M | M is needed at compile time but optional at runtime |
exports P | Public types in package P are accessible to all modules |
exports P to M | Package P is accessible only to the listed modules |
opens P / opens P to M | Allows deep reflection (including private members) on package P at runtime |
open module | Opens every package of the module for reflection |
uses S | This module looks up implementations of service S with ServiceLoader |
provides S with C | Class C in this module is an implementation of service S |
Rules worth knowing before you start:
- The file must be named
module-info.java, and a module has exactly one. - Directives use module names after
requiresand package names afterexportsandopens. - Every module reads
java.baseautomatically. Never writerequires java.base;. - Modules may not form cycles. If
ArequiresB,Bcannot requireA.
Note:
module,requires,exportsand the other directive words are restricted keywords. They have special meaning only insidemodule-info.java, so you can still usemoduleas a variable name elsewhere.
requires transitive: Passing a Dependency On
In the last lesson the app module needed two lines, because the service's public method returned Book from the model module:
module com.gocourse.library.app {
requires com.gocourse.library.service;
requires com.gocourse.library.model;
}
With requires transitive, the service module declares that anyone who reads it also reads the model module.
com.gocourse.library.service/module-info.java:
module com.gocourse.library.service {
requires transitive com.gocourse.library.model; // readers of service also read model
requires java.logging; // a JDK module, not in java.base
exports com.gocourse.library.service; // internal stays hidden
}
com.gocourse.library.app/module-info.java:
module com.gocourse.library.app {
requires com.gocourse.library.service; // model comes along automatically
}
Compile and inspect the service module:
javac -d out --module-source-path src $(find src -name "*.java")
java -p out --describe-module com.gocourse.library.service
Output (first line shortened):
com.gocourse.library.service file:///.../out/com.gocourse.library.service/
exports com.gocourse.library.service
requires java.logging
requires com.gocourse.library.model transitive
requires java.base mandated
contains com.gocourse.library.service.internal
How it works:
LibraryAppstill usesBookdirectly, and it compiles with only onerequires, because reading the service module implies reading the model module.- Use
requires transitivewhen types from another module appear in your exported API: as return types, parameter types or superclasses. HereavailableBooks()returnsList<Book>. java.loggingis used only inside the service, so a plainrequiresis right. Callers do not need it.- The JDK uses this too:
java.sqlhasrequires transitive java.loggingandjava.xml, as the previous lesson showed.
exports ... to: Qualified Exports
A plain exports shares a package with every module. A qualified export shares it only with modules you name, which is useful for admin or integration packages that should not become public API.
com.gocourse.pricing/module-info.java:
module com.gocourse.pricing {
exports com.gocourse.pricing.api; // to everyone
exports com.gocourse.pricing.admin to com.gocourse.dashboard; // to one friend module only
}
api/Prices.java and admin/TaxAdmin.java:
package com.gocourse.pricing.api;
public final class Prices {
private Prices() { }
public static double withTax(double amount) {
return amount * 1.18;
}
}
package com.gocourse.pricing.admin;
public final class TaxAdmin {
private TaxAdmin() { }
public static String currentRate() {
return "GST 18%";
}
}
The friend module, com.gocourse.dashboard, uses both packages:
module com.gocourse.dashboard {
requires com.gocourse.pricing;
}
package com.gocourse.dashboard;
import com.gocourse.pricing.admin.TaxAdmin;
import com.gocourse.pricing.api.Prices;
public class Dashboard {
public static void main(String[] args) {
System.out.println("Admin view: " + TaxAdmin.currentRate());
System.out.printf("1000 with tax = %.2f%n", Prices.withTax(1000));
}
}
javac -d out --module-source-path src $(find src -name "*.java")
java -p out -m com.gocourse.dashboard/com.gocourse.dashboard.Dashboard
Output:
Admin view: GST 18%
1000 with tax = 1180.00
A different module, com.gocourse.store, that also requires pricing cannot import the admin package:
src/com.gocourse.store/com/gocourse/store/Store.java:3: error: package com.gocourse.pricing.admin is not visible
import com.gocourse.pricing.admin.TaxAdmin;
^
(package com.gocourse.pricing.admin is declared in module com.gocourse.pricing, which does not export it to module com.gocourse.store)
1 error
How it works:
exports ... to com.gocourse.dashboardmakesadminvisible to the dashboard and to no one else.- The store module can still use
com.gocourse.pricing.api, because that package has an unqualified export. - List several friends with commas:
exports com.gocourse.pricing.admin to com.gocourse.dashboard, com.gocourse.audit;.
opens: Allowing Reflection on Private Members
exports gives access to public types at compile time and runtime. It does not allow reflection to break into private fields. Frameworks such as JSON mappers, Hibernate and Spring need that kind of deep reflection, so modules have a separate directive for it: opens.
com.gocourse.config holds a settings class with private fields:
module com.gocourse.config {
exports com.gocourse.config;
}
package com.gocourse.config;
public class AppSettings {
private String theme = "dark";
private int maxUsers = 50;
}
com.gocourse.inspector reads those fields with reflection, the way a framework would:
module com.gocourse.inspector {
requires com.gocourse.config;
}
package com.gocourse.inspector;
import com.gocourse.config.AppSettings;
import java.lang.reflect.Field;
public class Inspector {
public static void main(String[] args) throws IllegalAccessException {
AppSettings settings = new AppSettings();
for (Field field : AppSettings.class.getDeclaredFields()) {
field.setAccessible(true); // ask to bypass "private"
System.out.println(field.getName() + " = " + field.get(settings));
}
}
}
java -p out -m com.gocourse.inspector/com.gocourse.inspector.Inspector
Output:
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private java.lang.String com.gocourse.config.AppSettings.theme accessible: module com.gocourse.config does not "opens com.gocourse.config" to module com.gocourse.inspector
Add an opens directive to the config module and run again:
module com.gocourse.config {
exports com.gocourse.config;
opens com.gocourse.config to com.gocourse.inspector; // allow deep reflection
}
Output:
theme = dark
maxUsers = 50
How it works:
- The code compiles either way, because
AppSettingsis public and its package is exported. The failure happens at runtime, whensetAccessible(true)asks to bypassprivate. - The exception message names the exact directive that is missing, which makes these errors easy to fix.
opens ... togrants reflection to one module. A plainopens com.gocourse.config;would grant it to every module.
open module and --add-opens
| Option | Effect |
|---|---|
opens P; | Package P open to all modules at runtime |
opens P to M; | Package P open to module M only |
open module X { ... } | Every package in X is open; opens directives are then not allowed inside it |
java --add-opens X/P=M | Command-line override that opens P without changing module-info.java |
Writing open module com.gocourse.config { exports com.gocourse.config; } gives the same output as above. So does keeping the original descriptor and running:
java -p out --add-opens com.gocourse.config/com.gocourse.config=com.gocourse.inspector \
-m com.gocourse.inspector/com.gocourse.inspector.Inspector
Note:
opensaffects only runtime reflection. It never makes a package visible at compile time. A package can be both exported and opened, as in this example.
requires static: Optional Dependencies
requires static means "I need this module to compile, but my program can run without it". It suits optional features, such as PDF export that only some installations include.
module com.gocourse.pdf {
exports com.gocourse.pdf;
}
package com.gocourse.pdf;
public final class PdfWriter {
private PdfWriter() { }
public static String write(String text) {
return "[PDF] " + text;
}
}
module com.gocourse.reports {
requires static com.gocourse.pdf; // needed to compile, optional at runtime
}
package com.gocourse.reports;
public class ReportApp {
public static void main(String[] args) {
String report = "Monthly sales: Rs. 4,990.50";
boolean pdfAvailable = ModuleLayer.boot().findModule("com.gocourse.pdf").isPresent();
if (pdfAvailable) {
System.out.println(com.gocourse.pdf.PdfWriter.write(report));
} else {
System.out.println("[TEXT] " + report + " (PDF module not installed)");
}
}
}
Run it three ways:
# 1. PDF module not on the module path at all
java -p only-reports -m com.gocourse.reports/com.gocourse.reports.ReportApp
# 2. PDF module on the module path, but not added
java -p out -m com.gocourse.reports/com.gocourse.reports.ReportApp
# 3. PDF module on the path and added to the module graph
java -p out --add-modules com.gocourse.pdf -m com.gocourse.reports/com.gocourse.reports.ReportApp
Output:
[TEXT] Monthly sales: Rs. 4,990.50 (PDF module not installed)
[TEXT] Monthly sales: Rs. 4,990.50 (PDF module not installed)
[PDF] Monthly sales: Rs. 4,990.50
How it works:
- With a normal
requires, case 1 would fail at startup withFindException. Withrequires static, the app starts without the PDF module. - A
requires staticmodule is not resolved automatically, even when it sits on the module path (case 2). Something else must require it, or you add it with--add-modules(case 3). ModuleLayer.boot().findModule(...)checks whether the module was resolved, so the code never touchesPdfWriterwhen it is missing. Calling it anyway would throwNoClassDefFoundError.requires staticis also common for annotation-only libraries that are needed by the compiler but not at runtime.
uses and provides: Services With ServiceLoader
The last two directives connect service interfaces with implementations without either side knowing the other's class names.
- The consumer declares
uses Interface;and loads implementations withjava.util.ServiceLoader. - Each provider declares
provides Interface with ImplementationClass;. - The provider's package does not need to be exported.
ServiceLoadercreates the object for you.
If a module calls ServiceLoader.load(...) without a matching uses directive, it fails at runtime:
Exception in thread "main" java.util.ServiceConfigurationError: com.gocourse.payment.api.PaymentGateway: module com.gocourse.checkout does not declare `uses`
The real-world example below builds a complete service with two providers.
Real-World Example: Plug-In Payment Gateways
A checkout system should support UPI today and cards tomorrow without editing the checkout code. With uses and provides, each payment gateway is a separate module JAR: drop it on the module path to add it, remove it to disable it.
pay/src/
├── com.gocourse.payment.api/ exports the PaymentGateway interface
├── com.gocourse.payment.upi/ provides PaymentGateway with UpiGateway
├── com.gocourse.payment.card/ provides PaymentGateway with CardGateway
└── com.gocourse.checkout/ uses PaymentGateway
com.gocourse.payment.api:
module com.gocourse.payment.api {
exports com.gocourse.payment.api;
}
package com.gocourse.payment.api;
public interface PaymentGateway {
String name();
double feePercent();
default String pay(String orderId, double amount) {
double fee = amount * feePercent() / 100;
return String.format("%-5s paid %s: Rs. %.2f + fee Rs. %.2f", name(), orderId, amount, fee);
}
}
com.gocourse.payment.upi:
module com.gocourse.payment.upi {
requires com.gocourse.payment.api;
provides com.gocourse.payment.api.PaymentGateway
with com.gocourse.payment.upi.UpiGateway;
// no exports: UpiGateway is reachable only through ServiceLoader
}
package com.gocourse.payment.upi;
import com.gocourse.payment.api.PaymentGateway;
public class UpiGateway implements PaymentGateway {
@Override
public String name() {
return "UPI";
}
@Override
public double feePercent() {
return 0.0;
}
}
com.gocourse.payment.card:
module com.gocourse.payment.card {
requires com.gocourse.payment.api;
provides com.gocourse.payment.api.PaymentGateway
with com.gocourse.payment.card.CardGateway;
}
package com.gocourse.payment.card;
import com.gocourse.payment.api.PaymentGateway;
public class CardGateway implements PaymentGateway {
@Override
public String name() {
return "CARD";
}
@Override
public double feePercent() {
return 1.8;
}
}
com.gocourse.checkout:
module com.gocourse.checkout {
requires com.gocourse.payment.api;
uses com.gocourse.payment.api.PaymentGateway; // we will look up implementations
}
package com.gocourse.checkout;
import com.gocourse.payment.api.PaymentGateway;
import java.util.Comparator;
import java.util.List;
import java.util.ServiceLoader;
public class Checkout {
public static void main(String[] args) {
List<PaymentGateway> gateways = ServiceLoader.load(PaymentGateway.class).stream()
.map(ServiceLoader.Provider::get)
.sorted(Comparator.comparing(PaymentGateway::name))
.toList();
if (gateways.isEmpty()) {
System.out.println("No payment gateway installed.");
return;
}
System.out.println("Installed gateways: " + gateways.stream().map(PaymentGateway::name).toList());
for (PaymentGateway gateway : gateways) {
System.out.println(gateway.pay("ORD-1001", 2500.00));
}
PaymentGateway cheapest = gateways.stream()
.min(Comparator.comparingDouble(PaymentGateway::feePercent))
.orElseThrow();
System.out.println("Cheapest: " + cheapest.name() + " (module " + cheapest.getClass().getModule().getName() + ")");
}
}
Compile, package each module as a JAR, and run with every gateway installed:
javac -d out --module-source-path src $(find src -name "*.java")
mkdir -p mods
jar --create --file mods/payment-api.jar -C out/com.gocourse.payment.api .
jar --create --file mods/payment-upi.jar -C out/com.gocourse.payment.upi .
jar --create --file mods/payment-card.jar -C out/com.gocourse.payment.card .
jar --create --file mods/checkout.jar --main-class com.gocourse.checkout.Checkout -C out/com.gocourse.checkout .
java -p mods -m com.gocourse.checkout
Output:
Installed gateways: [CARD, UPI]
CARD paid ORD-1001: Rs. 2500.00 + fee Rs. 45.00
UPI paid ORD-1001: Rs. 2500.00 + fee Rs. 0.00
Cheapest: UPI (module com.gocourse.payment.upi)
Now remove payment-card.jar from the module path and run the same command:
Installed gateways: [UPI]
UPI paid ORD-1001: Rs. 2500.00 + fee Rs. 0.00
Cheapest: UPI (module com.gocourse.payment.upi)
With neither provider installed:
No payment gateway installed.
Check what a provider module declares:
jar --describe-module --file mods/payment-upi.jar
Output (after the first line):
requires com.gocourse.payment.api
requires java.base mandated
provides com.gocourse.payment.api.PaymentGateway with com.gocourse.payment.upi.UpiGateway
contains com.gocourse.payment.upi
How it works:
- The contract.
com.gocourse.payment.apiexports only thePaymentGatewayinterface. Every other module depends on this one small module. - Providers stay hidden. The UPI and card modules export nothing.
jar --describe-modulelists their package undercontains, so no code can writenew UpiGateway().provides ... withis the only way in. - The consumer never names a provider.
Checkoutdeclaresuses PaymentGatewayand callsServiceLoader.load(PaymentGateway.class). The module system finds every module on the module path thatprovidesthe interface and adds it to the module graph automatically, even though no modulerequiresthe providers. - Lazy creation.
ServiceLoader.stream()returnsProviderobjects.Provider::getcreates each gateway through its public no-argument constructor. A provider can instead declare apublic static PaymentGateway provider()method to control creation. - Plug-in behaviour. Adding or removing a JAR changes the available gateways without recompiling
Checkout. The empty-list check keeps the app working when no gateway is installed. - The numbers. The card fee is
2500.00 × 1.8 / 100 = 45.00; UPI has no fee, so it is the cheapest.
The JDK uses the same mechanism: java.sql declares uses java.sql.Driver, and each JDBC driver JAR provides an implementation, which is how the DriverManager from the database lessons finds MySQL or PostgreSQL drivers. For packaging these modules, revisit JAR File in Java, and for the access rules that exports builds on, see Access Control in Java.