Java Module requires and exports: Dependencies and Exported Packages
Declare Java module dependencies with requires and publish packages with exports: the "package is not visible" error, the module graph and readability, why requires is not transitive, hiding implementation packages, compiling and running multi-module apps, and split packages.
kvi5hnuCode Sprout team member9 min readOn this page
Two statements form the backbone of the module system. requires says which modules your module needs, and exports says which of your packages other modules may use. This article shows both in action, including the compiler errors you'll meet when one is missing, and builds a small library module with a hidden implementation.
Requiring modules
Let's make a module requiremod whose program uses a class from the desktop API, say java.awt.Point, or Swing's JOptionPane to show a dialog:
package com.example.hello;
import javax.swing.JOptionPane;
public class HelloWorld {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello, Modular World!");
}
}
With an empty module declaration, compilation fails:
error: package javax.swing is not visible
(package javax.swing is declared in module java.desktop, but module requiremod does not read it)
The JDK is modularized, and javax.swing and java.awt live in the java.desktop module. Our module must declare that it depends on it:
module requiremod {
requires java.desktop;
}
Explicit requirements are a design goal. Because each module lists what it needs, the virtual machine can check before starting the program that every requirement is met, so you don't get a NoClassDefFoundError an hour into production. The Hello World of article 111 didn't need this because it only used java.lang and java.io, which are in java.base. Every module requires java.base implicitly.
requires names a module, and exports (below) names a package. Mixing them up is a classic beginner error.
The module graph
Our module lists only its own requirements. java.desktop in turn declares its own: java.prefs, plus java.datatransfer and java.xml, which it requires transitively (article 115). java.prefs requires java.xml. Modules and their requires edges form the module graph, where java.base is implied for everyone:

The module graph can't have cycles. A module can't directly or indirectly require itself.
requires is not transitive
A module doesn't automatically pass its access rights on. java.desktop requires java.prefs, but that doesn't let our module use java.util.prefs. And java.prefs requiring java.xml doesn't by itself give java.desktop access to java.xml, which is why java.desktop declares that requirement explicitly. In mathematical terms, requires is not transitive. That's usually what you want, because every module states its real dependencies. Article 115 shows requires transitive, which relaxes the rule where it makes sense.
The compiler's message talks about reading. In JPMS terms, module M reads module N when
- M requires N, or
- M requires a module that transitively requires N, or
- N is M itself or
java.base.
Our module reads java.desktop, and also java.datatransfer and java.xml thanks to requires transitive, but not java.prefs. The demo proves it with a compile error.
Exporting packages
Requiring a module doesn't make all of its packages available. A module states which packages are accessible with exports. Here's part of the java.xml declaration:
module java.xml {
exports javax.xml;
exports javax.xml.catalog;
exports javax.xml.datatype;
exports javax.xml.namespace;
exports javax.xml.parsers;
...
}
It hides other packages, such as jdk.xml.internal, simply by not exporting them.
For an exported package, its public and protected types, and their public and protected members, are accessible outside the module. As always, protected means subclasses and the same package. A package that is not exported is inaccessible outside its module, even its public classes.
That's a real change from Java before modules, when any public class could be used. Programmers once routinely used internal classes such as sun.misc.BASE64Encoder (removed outright in Java 9) or com.sun.rowset.CachedRowSetImpl (now in an unexported package) when the public API was missing something. Now every JDK package lives in a module, and the unexported ones are off limits. Some old programs broke with Java 9 for that reason. Nobody ever promised those internals would stay available, though, and replacements such as java.util.Base64 exist. A few critical internals, notably sun.misc.Unsafe, remained reachable through the jdk.unsupported module to ease migration.
Example: a library with a hidden implementation
Let's write a module com.example.greet that follows the naming convention. It exports the package com.example.greet and keeps com.example.greet.internal to itself. The public interface has a factory method:
package com.example.greet;
public interface Greeter {
static Greeter newInstance() {
return new com.example.greet.internal.GreeterImpl();
}
String greet(String subject);
}
The implementation must be public because the other package uses it:
package com.example.greet.internal;
import com.example.greet.Greeter;
public class GreeterImpl implements Greeter {
public String greet(String subject) { return "Hello, " + subject + "!"; }
}
The module contains both packages but exports only the first:
module com.example.greet {
exports com.example.greet;
}
The application lives in a second module that requires the library:
module exportedpkg {
requires com.example.greet;
}
package com.example.hello;
import com.example.greet.Greeter;
public class HelloWorld {
public static void main(String[] args) {
Greeter greeter = Greeter.newInstance();
System.out.println(greeter.greet("Modular World"));
}
}
The source tree:
com.example.greet/
├── module-info.java
└── com/example/greet/
├── Greeter.java
└── internal/
└── GreeterImpl.java
exportedpkg/
├── module-info.java
└── com/example/hello/
└── HelloWorld.java
Build the library first, then the application with the library on the module path, then run with both on the module path (; instead of : on Windows):
javac -d mods/com.example.greet com.example.greet/module-info.java \
com.example.greet/com/example/greet/Greeter.java \
com.example.greet/com/example/greet/internal/GreeterImpl.java
javac -p mods -d mods/exportedpkg exportedpkg/module-info.java \
exportedpkg/com/example/hello/HelloWorld.java
java -p mods -m exportedpkg/com.example.hello.HelloWorld
In the Windows cmd shell, quote a module path containing a colon, and use ^ instead of \ to continue lines. For many modules, javac --module-source-path src -d out -m mod1,mod2 compiles them all at once, with each module in a subdirectory of src named after the module.
The implementation class is now truly hidden. Clients use the interface and the factory method, and they can't instantiate GreeterImpl themselves. Compiling new com.example.greet.internal.GreeterImpl() in another module fails with "package ... is not visible ... which does not export it". Even reflection is blocked at runtime: getConstructor().newInstance() throws IllegalAccessException. Article 113 shows how a module can deliberately open a package to reflection.
In IDEs, each JPMS module is usually a separate project or IDE module (in IntelliJ IDEA, a module with its own module-info.java). In Maven and Gradle, each JPMS module is a separate subproject, and the build tool puts dependencies on the module path automatically.
A complete example
The demo compiles real modules with javac, run in-process via ToolProvider, and runs them with java -p ... -m ... in a child process. It reproduces the "not visible" error and fixes it with requires java.desktop, lists what java.desktop itself requires, and proves that requires isn't transitive. It builds the greeter library and application, showing that the hidden implementation is blocked both at compile time and through reflection, and finally triggers the split-package error.
import java.io.*;
import java.lang.module.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
public class Solution {
static Path root;
static void source(String path, String text) throws IOException {
Path p = root.resolve("src").resolve(path);
Files.createDirectories(p.getParent());
Files.writeString(p, text);
}
/** Runs a JDK tool in-process; prints only the lines that matter. */
static boolean tool(String name, String... args) {
var out = new StringWriter();
int rc = ToolProvider.findFirst(name).orElseThrow()
.run(new PrintWriter(out, true), new PrintWriter(out, true), args);
out.toString().lines()
.filter(l -> l.contains("error:") || l.contains("(package") || l.contains("warning:"))
.map(l -> l.replace(root.toString() + File.separator, "").replace(File.separatorChar, '/'))
.forEach(l -> System.out.println(" " + l.strip()));
return rc == 0;
}
static void java(String... args) throws IOException, InterruptedException {
var cmd = new ArrayList<String>(List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString()));
cmd.addAll(List.of(args));
System.out.println(" $ java " + String.join(" ", args).replace(root.toString() + File.separator, ""));
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
new String(p.getInputStream().readAllBytes()).lines().forEach(l -> System.out.println(" " + l));
p.waitFor();
}
static String path(String rel) { return root.resolve(rel).toString(); }
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("mods");
System.out.println("-- using java.desktop without requiring it --");
source("requiremod/com/example/hello/HelloWorld.java", """
package com.example.hello;
import java.awt.Point;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello from a module that uses " + new Point(3, 4));
}
}
""");
source("requiremod/module-info.java", "module requiremod { }\n");
System.out.println(" compiles: " + tool("javac", "-d", path("out"), "--module-source-path", path("src"), "-m", "requiremod"));
System.out.println("-- after adding: requires java.desktop; --");
source("requiremod/module-info.java", "module requiremod {\n requires java.desktop;\n}\n");
System.out.println(" compiles: " + tool("javac", "-d", path("out"), "--module-source-path", path("src"), "-m", "requiremod"));
java("-p", path("out"), "-m", "requiremod/com.example.hello.HelloWorld");
System.out.println("-- what java.desktop itself requires --");
ModuleDescriptor desktop = ModuleLayer.boot().findModule("java.desktop").orElseThrow().getDescriptor();
desktop.requires().stream().map(r -> (r.modifiers().contains(ModuleDescriptor.Requires.Modifier.TRANSITIVE) ? "transitive " : "") + r.name())
.filter(s -> !s.endsWith("java.base")).sorted().forEach(s -> System.out.println(" requires " + s));
System.out.println("-- requires is not transitive: java.desktop's own java.prefs is not readable --");
source("prefsuser/module-info.java", "module prefsuser {\n requires java.desktop;\n}\n");
source("prefsuser/com/example/prefs/Use.java", """
package com.example.prefs;
public class Use { java.util.prefs.Preferences p; }
""");
System.out.println(" compiles: " + tool("javac", "-d", path("out"), "--module-source-path", path("src"), "-m", "prefsuser"));
System.out.println("-- exporting a package, hiding another --");
source("com.example.greet/module-info.java", """
module com.example.greet {
exports com.example.greet;
}
""");
source("com.example.greet/com/example/greet/Greeter.java", """
package com.example.greet;
public interface Greeter {
static Greeter newInstance() { return new com.example.greet.internal.GreeterImpl(); }
String greet(String subject);
}
""");
source("com.example.greet/com/example/greet/internal/GreeterImpl.java", """
package com.example.greet.internal;
import com.example.greet.Greeter;
public class GreeterImpl implements Greeter {
public String greet(String subject) { return "Hello, " + subject + "!"; }
}
""");
source("exportedpkg/module-info.java", """
module exportedpkg {
requires com.example.greet;
}
""");
source("exportedpkg/com/example/hello/HelloWorld.java", """
package com.example.hello;
import com.example.greet.Greeter;
public class HelloWorld {
public static void main(String[] args) throws Exception {
Greeter greeter = Greeter.newInstance();
System.out.println(greeter.greet("Modular World"));
System.out.println("implementation class: " + greeter.getClass().getName());
try {
Class<?> impl = Class.forName("com.example.greet.internal.GreeterImpl");
impl.getConstructor().newInstance();
} catch (IllegalAccessException e) {
System.out.println("reflection: IllegalAccessException, package not exported");
}
}
}
""");
// separately, as a real build would: library first, then the application with the library on the module path
System.out.println(" library compiles: " + tool("javac", "-d", path("mods/com.example.greet"),
path("src/com.example.greet/module-info.java"),
path("src/com.example.greet/com/example/greet/Greeter.java"),
path("src/com.example.greet/com/example/greet/internal/GreeterImpl.java")));
System.out.println(" application compiles: " + tool("javac", "-p", path("mods"), "-d", path("mods/exportedpkg"),
path("src/exportedpkg/module-info.java"), path("src/exportedpkg/com/example/hello/HelloWorld.java")));
java("-p", path("mods"), "-m", "exportedpkg/com.example.hello.HelloWorld");
System.out.println("-- using the hidden package directly does not compile --");
source("sneaky/module-info.java", "module sneaky {\n requires com.example.greet;\n}\n");
source("sneaky/com/example/sneaky/Sneak.java", """
package com.example.sneaky;
public class Sneak { Object g = new com.example.greet.internal.GreeterImpl(); }
""");
System.out.println(" compiles: " + tool("javac", "-p", path("mods"), "-d", path("mods/sneaky"),
path("src/sneaky/module-info.java"), path("src/sneaky/com/example/sneaky/Sneak.java")));
System.out.println("-- a package may not be in two modules --");
for (String m : List.of("first", "second")) {
source(m + "/module-info.java", "module " + m + " { exports com.example.shared; }\n");
source(m + "/com/example/shared/Util.java", "package com.example.shared; public class Util { }\n");
tool("javac", "-d", path("split/" + m), path("src/" + m + "/module-info.java"), path("src/" + m + "/com/example/shared/Util.java"));
}
source("both/module-info.java", "module both { requires first; requires second; }\n");
source("both/com/example/both/B.java", "package com.example.both; public class B { }\n");
System.out.println(" compiles: " + tool("javac", "-p", path("split"), "-d", path("split/both"),
path("src/both/module-info.java"), path("src/both/com/example/both/B.java")));
try (var walk = Files.walk(root)) { walk.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); }
}
}
-- using java.desktop without requiring it --
src/requiremod/com/example/hello/HelloWorld.java:2: error: package java.awt is not visible
(package java.awt is declared in module java.desktop, but module requiremod does not read it)
compiles: false
-- after adding: requires java.desktop; --
compiles: true
$ java -p out -m requiremod/com.example.hello.HelloWorld
Hello from a module that uses java.awt.Point[x=3,y=4]
-- what java.desktop itself requires --
requires java.prefs
requires transitive java.datatransfer
requires transitive java.xml
-- requires is not transitive: java.desktop's own java.prefs is not readable --
src/prefsuser/com/example/prefs/Use.java:2: error: package java.util.prefs is not visible
(package java.util.prefs is declared in module java.prefs, but module prefsuser does not read it)
compiles: false
-- exporting a package, hiding another --
library compiles: true
application compiles: true
$ java -p mods -m exportedpkg/com.example.hello.HelloWorld
Hello, Modular World!
implementation class: com.example.greet.internal.GreeterImpl
reflection: IllegalAccessException, package not exported
-- using the hidden package directly does not compile --
src/sneaky/com/example/sneaky/Sneak.java:2: error: package com.example.greet.internal is not visible
(package com.example.greet.internal is declared in module com.example.greet, which does not export it)
compiles: false
-- a package may not be in two modules --
src/both/module-info.java:1: error: module both reads package com.example.shared from both first and second
compiles: false
Common questions
What is the difference between requires and exports?
requires names a module your module depends on. exports names one of your packages that other modules may use. Mixing them up, such as writing a package name after requires, is a common beginner error.
Why do I get "package javax.swing is not visible"?
Your module doesn't read the module that contains the package. Add requires java.desktop; to module-info.java. To find which module contains a package, check the Javadoc, which lists the module at the top of each class page.
If my module requires A, and A requires B, can I use B's classes?
Only if A declares requires transitive B. A plain requires doesn't pass on readability. Otherwise, add requires B to your own module.
Why can't another module use my public class?
A public class is accessible outside its module only if its package is exported. Add exports your.package; to your module declaration, or keep it unexported on purpose to hide the implementation.
What is a split package, and how do I fix it? The same package appears in two modules. The module system forbids that, even if neither module exports the package. Rename or merge the packages, or, during migration, keep both JARs on the class path.
API reference
Module declaration statements
| Statement | Description |
|---|---|
requires module.name; | this module reads module.name and may use its exported packages |
exports package.name; | public and protected types of the package are accessible to modules that read this one |
Commands and reflection
| Item | Description |
|---|---|
javac -p modulepath ..., java -p modulepath -m module/main.Class | compile and run against modules on the module path |
javac --module-source-path src -d out -m m1,m2 | compile several modules at once (multi-module mode) |
Set<ModuleDescriptor.Requires> ModuleDescriptor.requires(), Requires.modifiers() | a module's requirements and modifiers such as TRANSITIVE |
boolean Module.canRead(Module other), boolean Module.isExported(String pn) | readability and export checks at runtime |
Summary
requiresnames a module you depend on. Without it, using that module's packages fails with "package ... is not visible ... does not read it".java.baseis always read.- Requirements form an acyclic module graph that the JVM checks before startup.
requiresisn't transitive, so declare every module you use directly. exportsnames a package whose public and protected API becomes accessible. Unexported packages are hidden from other modules at compile time and from reflection at runtime, even their public classes. That's why JDK internals such ascom.sun.rowset.CachedRowSetImplare off limits now.- Hide implementations behind exported interfaces and factory methods. Packages must be unique across modules, so split packages are errors.
Practice Questions
Your module uses java.sql.Connection and compilation fails with "package java.sql is not visible". What do you add?
Add requires java.sql; to your module-info.java. The package java.sql belongs to the module java.sql, which your module must read.
Module A requires B, and B requires C. Can code in A use the exported packages of C?
Not unless B declares requires transitive C. Plain requires isn't transitive, so A reads only B (and java.base). A should add requires C itself if it uses C directly.
A class in an unexported package is public. Can another module use it?
No. Outside its module, an unexported package is inaccessible, both at compile time and by default through reflection, whatever its classes' access modifiers. Only exported packages, or opened packages for reflection, are visible.
What is the difference between the names after requires and after exports?
requires is followed by a module name, and exports by a package name. They often look alike when a module is named after its top-level package.
Two libraries both contain the package org.util, and your module requires both. What happens?
That's a split package. Compilation fails ("module reads package org.util from both ..."), and the JVM won't start such a configuration. A package may belong to only one module in a configuration.
Previous: Java Modules Introduction: The Module Concept and a Hello World Module
Next: Modular JARs and Reflective Access in Java: opens and open modules
Related reading
- Java Modules Introduction: The Module Concept and a Hello World Module
- Your First Java Program Explained: Classes, main, Statements and Comments
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values
- Java Annotation Processors: Generating Source Code at Compile Time

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.