Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

module / requires / exports

A module declaration in module-info.java: which modules it needs and which packages it exposes to others.

Available since: Java 9

Syntax

module name { requires other.module; exports some.package; }

Examples

The module-info.java file at the root of the sources:

// src/module-info.java
module com.shop.app {
    requires java.net.http;
    requires java.sql;
    exports com.shop.api;
}

Which module a class belongs to and which packages a module exports:

void main() {
    IO.println(String.class.getModule().getName());
 
    Module sql = java.sql.Connection.class.getModule();
    IO.println(sql.getName());
    IO.println(sql.getDescriptor().exports().stream()
        .map(ModuleDescriptor.Exports::source)
        .sorted()
        .toList());
 
    IO.println(getClass().getModule().isNamed());
}

Output:

java.base
java.sql
[java.sql, javax.sql]
false

Notes

requires brings in a module, exports makes a package's public classes available to other modules; unexported packages are hidden even from public. requires transitive passes a dependency on, opens allows reflection (needed by frameworks such as Spring and Jackson). Code without module-info.java ends up in the unnamed module and sees everything — that is how most applications and all examples in this reference work. A modular project is usually built by Maven or Gradle and run through the module path: java -p out -m com.shop.app/com.shop.app.Main.

See also

In the tutorial

  • Modules — The Java module system — module-info.java, requires and exports, a two-module project, compiling with javac --module-source-path and running with java --module-path, and the modules of the JDK itself.

Thanks for reading!

Donate to the site — we work hard for you.