module-info in Java: Every Module Directive Explained

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 230 of 306

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];
}
DirectivePurpose
requires MThis module reads module M (needs it to compile and run)
requires transitive MThis module reads M, and every module that reads this one also reads M
requires static MM is needed at compile time but optional at runtime
exports PPublic types in package P are accessible to all modules
exports P to MPackage P is accessible only to the listed modules
opens P / opens P to MAllows deep reflection (including private members) on package P at runtime
open moduleOpens every package of the module for reflection
uses SThis module looks up implementations of service S with ServiceLoader
provides S with CClass 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 requires and package names after exports and opens.
  • Every module reads java.base automatically. Never write requires java.base;.
  • Modules may not form cycles. If A requires B, B cannot require A.

Note: module, requires, exports and the other directive words are restricted keywords. They have special meaning only inside module-info.java, so you can still use module as 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:

  • LibraryApp still uses Book directly, and it compiles with only one requires, because reading the service module implies reading the model module.
  • Use requires transitive when types from another module appear in your exported API: as return types, parameter types or superclasses. Here availableBooks() returns List<Book>.
  • java.logging is used only inside the service, so a plain requires is right. Callers do not need it.
  • The JDK uses this too: java.sql has requires transitive java.logging and java.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.dashboard makes admin visible 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 AppSettings is public and its package is exported. The failure happens at runtime, when setAccessible(true) asks to bypass private.
  • The exception message names the exact directive that is missing, which makes these errors easy to fix.
  • opens ... to grants reflection to one module. A plain opens com.gocourse.config; would grant it to every module.

open module and --add-opens

OptionEffect
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=MCommand-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: opens affects 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 with FindException. With requires static, the app starts without the PDF module.
  • A requires static module 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 touches PdfWriter when it is missing. Calling it anyway would throw NoClassDefFoundError.
  • requires static is 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 with java.util.ServiceLoader.
  • Each provider declares provides Interface with ImplementationClass;.
  • The provider's package does not need to be exported. ServiceLoader creates 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:

  1. The contract. com.gocourse.payment.api exports only the PaymentGateway interface. Every other module depends on this one small module.
  2. Providers stay hidden. The UPI and card modules export nothing. jar --describe-module lists their package under contains, so no code can write new UpiGateway(). provides ... with is the only way in.
  3. The consumer never names a provider. Checkout declares uses PaymentGateway and calls ServiceLoader.load(PaymentGateway.class). The module system finds every module on the module path that provides the interface and adds it to the module graph automatically, even though no module requires the providers.
  4. Lazy creation. ServiceLoader.stream() returns Provider objects. Provider::get creates each gateway through its public no-argument constructor. A provider can instead declare a public static PaymentGateway provider() method to control creation.
  5. 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.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about module-info in Java: Every Module Directive Explained and get answers drawn from it.

Signed-in readers only.