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]
falseNotes
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
- import / package — package sets the file's package, import lets you use short names of classes from other packages.
- public / protected / private — Access modifiers control where a class, field, method or constructor is visible from.
- Object.getClass() — Returns the runtime class of an object.
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.