Java Module Declarations: requires, requires transitive, exports and opens (OCP 21)
The module-info.java directives for the OCP 21 exam: exports and qualified exports, what exporting a package really exposes, requires, requires transitive and implied readability, requires static, duplicate and cyclic requires, and opens, opens to and open modules for reflection.
kvi5hnuCode Sprout team member10 min readOn this page
The previous article connected two modules with one exports and one requires. A module declaration can say much more than that. This article covers every directive that controls access: who may compile against a package, which dependencies pass on to callers, and who may use reflection. The two service directives, provides and uses, come in the next article.
The examples use three modules of a small shop application:
shop.stockholds the product classes.shop.tilluses them to ring up sales.shop.webshows a web page and usesshop.till.
Directives can appear in any order inside the braces, and each one ends with a semicolon.
exports: sharing a package
module shop.stock {
exports shop.stock; // every module that reads shop.stock
exports shop.stock.price to shop.till; // only shop.till
exports shop.stock.audit to shop.till, shop.web;
}
exports <package>makes the package available to every module that reads this one.exports <package> to <module>, <module>is a qualified export: only the named modules get access. Any other module that tries to import the package getspackage shop.stock.price is not visible, exactly as if it weren't exported.- Use a qualified export when a package is meant for a few trusted modules, not for the world. It's good design even if no other module needs the package yet, because you can't know which modules will appear later.
Rules the compiler enforces:
- The package must exist in the module and contain at least one type ("package is empty or does not exist").
- A package can be exported only once. Writing
exports p;and alsoexports p to m;fails with "duplicate or conflicting exports", and so does naming the same target twice. - A target module that can't be found is only a warning (
module not found), not an error. The modules on each side are often compiled separately, so the target may not exist yet.
What exactly is exported?
Exporting a package exposes its public types: classes, interfaces, enums, records and annotation types. Within those types, the usual member rules then apply:
| Member access | Code in the same module | Code in another module |
|---|---|---|
private | Only inside the class | No access |
| package (no modifier) | Only inside the package | No access |
protected | Same package, or subclasses | Subclasses only, and only if the package is exported |
public | Everywhere | Only if the package is exported |
In other words, exports doesn't widen access. It decides whether public and protected reach beyond the module at all. A public class in a package that isn't exported acts like a package-private class to the outside world. A subclass in another module can call an inherited protected method, but an unrelated class there gets "has protected access", just as it would between packages.
requires: depending on a module
requires shop.stock; means "this module reads shop.stock". The current module can then compile against every package shop.stock exports to it. If shop.stock is missing, javac reports module not found, and java stops at startup with a FindException.
Two rules catch people out:
- No duplicates. The same module can't be named twice, not even once with
requiresand once withrequires transitive. The error isduplicate requires: shop.stock. - No cycles. If
shop.stockrequiresshop.tillandshop.tillrequiresshop.stock, both fail with "cyclic dependence involving ...". Move the shared types into a third module that both can require.
requires transitive: passing a dependency on
Suppose shop.till has this public method:
package shop.till;
import shop.stock.Item;
public class Till {
public Item scan() { return new Item(); }
}
Anyone who calls scan() gets an Item, a type from shop.stock. With a plain requires shop.stock; in shop.till, a module that requires only shop.till still can't use Item:
module shop.web {
requires shop.till;
}
import shop.stock.Item; // error: package shop.stock is not visible
...
var item = new Till().scan();
item.name(); // error: Item.name() in package shop.stock is not accessible
The second error is easy to miss. Even without naming the type, through var, shop.web may not call methods of a type from a module it doesn't read.
There are two fixes. shop.web could add its own requires shop.stock;. The better fix is for shop.till to declare that its callers need shop.stock too:
module shop.till {
exports shop.till;
requires transitive shop.stock;
}
Now every module that requires shop.till automatically reads shop.stock as well. This is called implied readability. With this declaration:
shop.tillitself needsshop.stockto compile and to run, exactly as with plainrequires.shop.webneeds onlyrequires shop.till;to useItem. It may also writerequires shop.stock;. That's redundant but legal, because it's in a different module.shop.webcan't be compiled or run withoutshop.stockbeing present, even though its own declaration never mentions it.- The effect chains. If
shop.webdeclaredrequires transitive shop.till;, any module requiringshop.webwould readshop.tilland, through it,shop.stock.

requires static: needed to compile, optional at run time
module shop.till {
requires static shop.reports;
}
requires static makes a dependency mandatory at compile time but optional at run time. If shop.reports isn't on the module path when the program starts, the JVM doesn't complain, and the module isn't loaded. Even when it is present, it's only resolved if something else needs it (or you add --add-modules shop.reports). The code must check that the module is available before using it. This is used for optional integrations and annotation-only dependencies. The modifiers can be combined as requires static transitive.
opens: allowing reflection
Reflection lets code inspect and call classes it didn't know about at compile time, even private members via setAccessible(true). Frameworks for JSON mapping, dependency injection and persistence rely on it. Because reflection can bypass encapsulation, a module must explicitly allow it:
module shop.stock {
exports shop.stock;
opens shop.stock.price; // reflection allowed for every module
opens shop.stock.audit to shop.web; // reflection only for shop.web
}
opens is about run time only:
- An opened package that isn't exported still can't be imported by other modules:
package shop.stock.price is not visible. - At run time, any module may reflect on everything in an opened package, including private members.
- An exported package that isn't opened allows reflection on its public members only. Calling
setAccessible(true)on a private field throwsInaccessibleObjectException. - A package that is neither exported nor opened can't be accessed even reflectively. Calling its public methods throws
IllegalAccessException. - A package may be both exported and opened. That's allowed and common for data classes that a framework fills in.
open module: opening every package
To open all packages at once, put the open modifier on the module itself:
open module shop.stock {
exports shop.stock;
}
Notice that the modifier is open while the directive is opens. An open module may still use exports and requires, but it can't contain any opens directive, because everything is already open. The error is 'opens' only allowed in strong modules. "Strong module" is the specification's name for a module that isn't open.
All the directives
| Directive | Meaning | Covered in |
|---|---|---|
exports p; / exports p to m; | Lets other modules (or only m) use package p | this article |
requires m; / requires transitive m; | Depends on module m (and passes it on) | this article |
requires static m; | m is needed to compile, optional at run time | this article |
opens p; / opens p to m; | Allows reflection on package p | this article |
uses T; | This module looks up implementations of service T | article 75 |
provides T with C; | This module supplies implementation C of service T | article 75 |
What's current
- These directives haven't changed since Java 9. Everything here is valid in Java 21 and Java 25.
- The JDK's own internal packages are strongly encapsulated. Java 9 to 15 only warned about illegal reflective access. Java 16 denied it by default, and Java 17 removed the
--illegal-accessswitch altogether. Code that reflects into JDK internals now needs explicit--add-openscommand-line options (article 76). - The
missing-explicit-ctorlint (Java 16+) warns about public classes in exported packages that rely on a default constructor. That's one more reason exported API classes often declare their constructors explicitly.
Exam traps from this article
A complete example
This program writes the three shop modules to a temporary folder and compiles them together with javac --module-source-path, called in-process through ToolProvider. It shows the compile errors for a missing transitive, a duplicate requires, importing an opened-but-not-exported package, and opens inside an open module. Then it builds the final version, prints each module's descriptor, and runs shop.web. That module calls into shop.till, then uses reflection on a private field in an exported package and on one in an opened package.
import java.io.*;
import java.lang.module.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
import java.util.stream.Collectors;
public class Solution {
static Path root;
static void write(String file, String code) throws IOException {
Path p = root.resolve("src").resolve(file);
Files.createDirectories(p.getParent());
Files.writeString(p, code);
}
// Compiles every module under src/ in one go and prints any errors.
static boolean compileAll(String label) throws IOException {
List<String> args = new ArrayList<>(List.of(
"-d", root.resolve("out").toString(),
"--module-source-path", root.resolve("src").toString()));
try (var files = Files.walk(root.resolve("src"))) {
files.filter(f -> f.toString().endsWith(".java"))
.sorted()
.forEach(f -> args.add(f.toString()));
}
var err = new StringWriter();
int code = ToolProvider.findFirst("javac").orElseThrow()
.run(new PrintWriter(Writer.nullWriter()), new PrintWriter(err),
args.toArray(String[]::new));
System.out.println(label + " -> " + (code == 0 ? "compiles" : "FAILS"));
err.toString().lines()
.filter(l -> l.contains("error:"))
.forEach(l -> System.out.println(" " + l.substring(l.indexOf("error:"))));
return code == 0;
}
static String describe(ModuleDescriptor d) {
String req = d.requires().stream()
.filter(r -> !r.name().equals("java.base"))
.map(r -> (r.modifiers().isEmpty() ? "" : r.modifiers().stream()
.map(m -> m.toString().toLowerCase(Locale.ROOT))
.sorted().collect(Collectors.joining(" ", "", " "))) + r.name())
.sorted().collect(Collectors.joining(", "));
String exp = d.exports().stream()
.map(e -> e.source() + (e.isQualified() ? " to " + new TreeSet<>(e.targets()) : ""))
.sorted().collect(Collectors.joining(", "));
String opn = d.opens().stream().map(ModuleDescriptor.Opens::source)
.sorted().collect(Collectors.joining(", "));
return String.format("%-11s requires [%s] exports [%s] opens [%s]", d.name(), req, exp, opn);
}
static void deleteTree(Path dir) throws IOException {
try (var paths = Files.walk(dir)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
}
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("shop");
try {
// shop.stock: one exported package, one opened (but not exported) package
write("shop.stock/shop/stock/Item.java", """
package shop.stock;
public class Item {
private final String secret = "cost=4";
public Item() { }
public String name() { return "pen"; }
}
""");
write("shop.stock/shop/stock/price/Tag.java", """
package shop.stock.price;
public class Tag {
private final String secret = "margin=60%";
public Tag() { }
}
""");
write("shop.stock/module-info.java", """
module shop.stock {
exports shop.stock;
opens shop.stock.price;
}
""");
// shop.till returns an Item from its public API
write("shop.till/shop/till/Till.java", """
package shop.till;
import shop.stock.Item;
public class Till {
public Till() { }
public Item scan() { return new Item(); }
}
""");
// shop.web uses Till AND names Item directly
write("shop.web/shop/web/Page.java", """
package shop.web;
import shop.stock.Item;
import shop.till.Till;
public class Page {
public static void main(String[] args) throws Exception {
Item item = new Till().scan();
System.out.println(" page shows " + item.name());
peek(item);
peek(Class.forName("shop.stock.price.Tag").getConstructor().newInstance());
}
static void peek(Object o) throws Exception {
var field = o.getClass().getDeclaredField("secret");
String who = o.getClass().getSimpleName();
try {
field.setAccessible(true);
System.out.println(" reflection read " + who + ".secret = " + field.get(o));
} catch (RuntimeException e) {
System.out.println(" reflection on " + who + ": " + e.getClass().getSimpleName());
}
}
}
""");
write("shop.web/module-info.java", """
module shop.web {
requires shop.till;
}
""");
System.out.println("== 1. shop.till says 'requires shop.stock;'");
write("shop.till/module-info.java", """
module shop.till {
exports shop.till;
requires shop.stock;
}
""");
compileAll(" build");
System.out.println("\n== 2. shop.till says 'requires transitive shop.stock;'");
write("shop.till/module-info.java", """
module shop.till {
exports shop.till;
requires transitive shop.stock;
}
""");
compileAll(" build");
System.out.println("\n== 3. Repeating a module in requires");
write("shop.till/module-info.java", """
module shop.till {
exports shop.till;
requires shop.stock;
requires transitive shop.stock;
}
""");
compileAll(" build");
write("shop.till/module-info.java", """
module shop.till {
exports shop.till;
requires transitive shop.stock;
}
""");
System.out.println("\n== 4. shop.web imports shop.stock.price (opened, not exported)");
Path page = root.resolve("src/shop.web/shop/web/Page.java");
String original = Files.readString(page);
Files.writeString(page, original.replace("import shop.till.Till;",
"import shop.till.Till;\nimport shop.stock.price.Tag;"));
compileAll(" build");
Files.writeString(page, original);
System.out.println("\n== 5. An open module can't also use 'opens'");
Path stockInfo = root.resolve("src/shop.stock/module-info.java");
String stock = Files.readString(stockInfo);
Files.writeString(stockInfo, "open " + stock);
compileAll(" build");
Files.writeString(stockInfo, stock);
System.out.println("\n== 6. Final build, descriptors and a run");
compileAll(" build");
ModuleFinder finder = ModuleFinder.of(root.resolve("out"));
finder.findAll().stream().map(ModuleReference::descriptor)
.sorted(Comparator.comparing(ModuleDescriptor::name))
.forEach(d -> System.out.println(" " + describe(d)));
ModuleLayer boot = ModuleLayer.boot();
Configuration cf = boot.configuration().resolve(finder, ModuleFinder.of(), Set.of("shop.web"));
ModuleLayer.Controller ctl = ModuleLayer.defineModulesWithOneLoader(
cf, List.of(boot), ClassLoader.getSystemClassLoader());
ModuleLayer layer = ctl.layer();
// The java launcher may start main() in a package that isn't exported.
// Code outside the module may not, so we grant this one call access.
ctl.addExports(layer.findModule("shop.web").orElseThrow(), "shop.web", Solution.class.getModule());
System.out.println(" shop.web reads shop.stock? "
+ layer.findModule("shop.web").orElseThrow()
.canRead(layer.findModule("shop.stock").orElseThrow()));
layer.findLoader("shop.web").loadClass("shop.web.Page")
.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
} finally {
deleteTree(root);
}
}
}
Output:
== 1. shop.till says 'requires shop.stock;'
build -> FAILS
error: package shop.stock is not visible
== 2. shop.till says 'requires transitive shop.stock;'
build -> compiles
== 3. Repeating a module in requires
build -> FAILS
error: duplicate requires: shop.stock
== 4. shop.web imports shop.stock.price (opened, not exported)
build -> FAILS
error: package shop.stock.price is not visible
== 5. An open module can't also use 'opens'
build -> FAILS
error: 'opens' only allowed in strong modules
== 6. Final build, descriptors and a run
build -> compiles
shop.stock requires [] exports [shop.stock] opens [shop.stock.price]
shop.till requires [transitive shop.stock] exports [shop.till] opens []
shop.web requires [shop.till] exports [] opens []
shop.web reads shop.stock? true
page shows pen
reflection on Item: InaccessibleObjectException
reflection read Tag.secret = margin=60%
Points to notice:
- Build 1 failed in
shop.web: plainrequires shop.stock;inshop.tilldidn't letshop.webseeItem. Build 2 changed only that one word, torequires transitive. - Naming
shop.stocktwice, once withtransitiveand once without, is a duplicate. shop.stock.priceis opened but not exported, so importing it fails at compile time…- …yet at run time reflection read its private field, while the same reflection on
Itemin the merely exportedshop.stockpackage threwInaccessibleObjectException. - The descriptor of
shop.weblists onlyshop.till, butcanReadreports that it readsshop.stock, through implied readability. - The program had to call
addExportson the layer's controller before invokingPage.mainthrough reflection, becauseshop.webexports nothing. Thejavalauncher has no such restriction, as article 73 noted.
Common questions
Should I always use requires transitive?
No. Use it when your exported API exposes types from the other module, such as return types, parameter types or superclasses. If you use the other module only internally, plain requires keeps your callers from depending on it by accident.
Can I export a package to a module that doesn't exist yet?
Yes. javac only warns. The qualified export takes effect once that module is present.
Does opens let others call my private methods without setAccessible?
No. Normal Java code still follows the access rules. opens only lets reflection call setAccessible(true) successfully.
Can a module require itself? No. That's the smallest possible cycle, and it fails with "cyclic dependence".
Summary
exports p [to m...]shares a package's public types with all modules or only named ones. Exports are per package and can't be duplicated.requires mreads a module.requires transitive malso makes every caller readm.requires static mis optional at run time. Duplicates and cycles don't compile.opens p [to m...]allows run-time reflection, including private members, but not compile-time use.open moduleopens every package and forbidsopensdirectives.- Directives can appear in any order.
Practice quiz
Test yourself with the module declarations quiz: 10 exam-style questions with explanations.
Previous: Java Modules: Benefits, module-info.java, Compiling, Running and Packaging (OCP 21)
Next: Java Module Services: Service Provider Interface, ServiceLoader, uses and provides (OCP 21)
Related reading
- Java Modules: Benefits, module-info.java, Compiling, Running and Packaging (OCP 21)
- User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
- Java Resource Bundles: Properties Files, Lookup Order, MessageFormat and Properties (OCP 21)
- Java Locales: Localizing Numbers, Currency, Percentages, Compact Numbers and Dates (OCP 21)
- Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.