Java Automatic Modules, the Unnamed Module and Migration Flags
Migrate Java applications to modules step by step: automatic modules from plain JARs, how their names are derived, Automatic-Module-Name, the unnamed module and class path, bottom-up migration, and the --add-exports, --add-opens and @argfile launcher options.
kvi5hnuCode Sprout team member9 min readOn this page
Designing modules for a brand-new project in which you write every line yourself is easy. That scenario is extremely rare, though. Almost every project depends on third-party libraries, and many of them still ship as plain JARs without a module-info.class. You could wait until all of them are modularized, but you don't have to. JPMS offers two bridges between the pre-modular world and fully modular applications: automatic modules and the unnamed module. This article covers both, plus the command-line flags that keep legacy code running on a modular JDK.
Automatic modules
Put any JAR on the module path instead of the class path, and it becomes a module. A JAR without module-info.class on the module path is an automatic module with these properties:
- It implicitly requires all other modules. It reads every module, including the unnamed module, so its own dependencies may stay on the class path.
- All of its packages are exported and opened.
- If its manifest
META-INF/MANIFEST.MFhas anAutomatic-Module-Nameentry, that value is the module name. - Otherwise the name is derived from the JAR file name. A trailing version number is dropped, and every sequence of non-alphanumeric characters becomes a single dot.
The first two rules mean the classes behave much as if they were on the class path. The point of putting the JAR on the module path is for the benefit of other modules, which can now express a dependency on it with requires.
Suppose your module processes CSV files with Apache Commons CSV. If you put commons-csv-1.9.0.jar on the module path, its name is commons.csv. The version -1.9.0 is dropped and - becomes a dot. Your declaration then says:
@SuppressWarnings("module") // silences the "automatic module" lint warning
module automod {
requires commons.csv;
}
A file-name-derived name is fragile. It depends on how somebody named the file, and it's probably not what the module will be called once it becomes a real module. Library maintainers should claim a name they control, ideally the top-level package, with one manifest line:
Automatic-Module-Name: org.apache.commons.csv
Commons CSV did exactly that starting with version 1.10.0, so with that JAR you write requires org.apache.commons.csv;. When the library eventually adds a real module-info.java with the same name, every module that refers to it keeps working.
Compiling and running a module that uses the automatic module works with both on the module path:
javac -p automod:commons-csv-1.10.0.jar -d mods/automod \
automod/module-info.java automod/com/example/places/CSVDemo.java
java -p mods:commons-csv-1.10.0.jar -m automod/com.example.places.CSVDemo
The unnamed module
Every class that is not on the module path, meaning everything on the class path, belongs to an unnamed module. Technically there can be several, one per class loader, but together they act like one. Like automatic modules, the unnamed module reads every module and exports and opens all its packages. That's why ordinary class-path programs keep working on Java 9 and later.
However, no explicit module can read the unnamed module. An explicit module is one with a module-info.class on the module path, as opposed to automatic or unnamed modules. There's no way to write requires for the class path, which keeps explicit modules free from "class path hell". If you put the CSV library on the class path while your module requires it, the program doesn't start:
Error occurred during initialization of boot layer
java.lang.module.FindException: Module org.example.csvlite not found, required by automod

So migration necessarily goes bottom-up:
- The Java platform itself was modularized in Java 9.
- Next, libraries are modularized, either as automatic modules or as explicit modules.
- Once every library your application uses is on the module path, you can turn your application code into modules.
Because automatic modules can read the unnamed module, the dependencies of an automatic module can stay on the class path during the transition.
Command-line flags for migration
Even if you never write a module, you live in the modular world. Your code sits on the class path in the unnamed module, but it talks to a modularized JDK whose internal packages are encapsulated. The rules tightened gradually:
- Since Java 9, compile-time access to non-exported JDK packages fails.
- Java 9 to 15 still permitted runtime reflective access to JDK internals, printing a warning on the first illegal access. The launcher flag
--illegal-accesshad four settings:permit(the Java 9 default),warn(a message for every access),debug(a message plus stack trace) anddeny. - Java 16 made
denythe default (JEP 396), and Java 17 removed the flag altogether (JEP 403). JDK internals are now strongly encapsulated, apart from critical APIs such assun.misc.Unsafeinjdk.unsupported.
When a legacy application needs an internal API and you can't fix its source code, two flags punch exactly the holes you need.
--add-exports module/package=target exports a package to a target module. To export to class-path code, the target is ALL-UNNAMED. For example, an old application that uses the internal class com.sun.rowset.CachedRowSetImpl can be started with:
java --add-exports java.sql.rowset/com.sun.rowset=ALL-UNNAMED -jar MyApp.jar
The proper fix is to use the public API. Since Java 7, RowSetProvider.newFactory().createCachedRowSet() gives you a cached row set.
--add-opens module/package=target opens a package for deep reflection. Reflection within the unnamed module is still fine, but private and protected members of platform classes are off limits. Some libraries that generate classes at runtime call the protected ClassLoader.defineClass through reflection, and they need:
--add-opens java.base/java.lang=ALL-UNNAMED
javac accepts --add-exports as well. --add-reads and --patch-module exist for rarer cases. Executable JARs can carry Add-Exports and Add-Opens attributes in their manifest, so users don't need the flags.
Argument files
Adding all these options can produce the command line from hell. Put them into files and pass the files with an @ prefix:
java @options1 @options2 -jar MyProg.jar
The syntax rules for these files are:
- Separate options with spaces, tabs or newlines.
- Use double quotes around arguments that contain spaces, such as
"Program Files". - A line ending in
\is joined with the next line. - Backslashes must be escaped, as in
C:\\Users\\Fred. - Lines starting with
#are comments.
javac supports @argfiles too, which is handy for long source lists.
A complete example
The demo builds a small non-modular "third-party" CSV library and copies its JAR under several file names to show how automatic module names are derived. It then builds a second JAR with Automatic-Module-Name in its manifest, lets an explicit module require it, and runs the program. Next it moves the library to the class path and shows the FindException. Finally, a legacy class-path program fails at deep reflection into java.lang and at calling an internal JDK class, and then succeeds once --add-opens and --add-exports are given, both directly and through an @argfile.
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);
}
static String clean(String s) {
return s.replace(root.toUri().toString(), "").replace(root.toString() + File.separator, "")
.replace(root.toString(), "").replace(File.separatorChar, '/');
}
static void 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.isBlank()).forEach(l -> System.out.println(" " + clean(l)));
if (rc != 0) System.out.println(" " + name + " failed");
}
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 " + clean(String.join(" ", args)).replace(File.pathSeparator, ":"));
Process p = new ProcessBuilder(cmd).directory(root.toFile()).redirectErrorStream(true).start();
new String(p.getInputStream().readAllBytes()).lines()
.filter(l -> !l.strip().startsWith("at ") && !l.isBlank())
.forEach(l -> System.out.println(" " + clean(l)));
p.waitFor();
}
static String p(String rel) { return root.resolve(rel).toString(); }
static String mp(String... rels) { return String.join(File.pathSeparator, Arrays.stream(rels).map(Solution::p).toList()); }
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("mods");
// a small "third-party" library that is NOT modular (no module-info)
source("csvlite/org/example/csvlite/Csv.java", """
package org.example.csvlite;
import java.util.*;
public class Csv {
public static List<Map<String, String>> parse(List<String> lines) {
String[] header = lines.get(0).split(",");
var rows = new ArrayList<Map<String, String>>();
for (String line : lines.subList(1, lines.size())) {
String[] cells = line.split(",");
var row = new LinkedHashMap<String, String>();
for (int i = 0; i < header.length; i++) row.put(header[i], cells[i]);
rows.add(row);
}
return rows;
}
}
""");
tool("javac", "-d", p("classes/csvlite"), p("src/csvlite/org/example/csvlite/Csv.java"));
Files.createDirectories(root.resolve("lib"));
tool("jar", "-c", "-f", p("lib/csvlite-1.9.0.jar"), "-C", p("classes/csvlite"), ".");
System.out.println("-- automatic module names --");
for (String name : List.of("csvlite-1.9.0.jar", "commons-csv-1.9.0.jar", "jackson_core-2.17.1.jar", "my--fancy..lib.jar")) {
Path dir = Files.createDirectories(root.resolve("names/" + name.hashCode()));
Files.copy(root.resolve("lib/csvlite-1.9.0.jar"), dir.resolve(name));
ModuleDescriptor d = ModuleFinder.of(dir).findAll().iterator().next().descriptor();
System.out.printf(" %-26s -> %s (automatic: %s, exports %s)%n", name, d.name(), d.isAutomatic(), d.packages());
}
Files.writeString(root.resolve("manifest.txt"), "Automatic-Module-Name: org.example.csvlite\n");
Files.createDirectories(root.resolve("lib2"));
tool("jar", "-c", "-f", p("lib2/csvlite-1.10.0.jar"), "-m", p("manifest.txt"), "-C", p("classes/csvlite"), ".");
ModuleDescriptor named = ModuleFinder.of(root.resolve("lib2")).findAll().iterator().next().descriptor();
System.out.println(" csvlite-1.10.0.jar with Automatic-Module-Name -> " + named.name());
System.out.println("-- an explicit module requiring the automatic module --");
Files.writeString(root.resolve("countries.csv"), "Name,Area\nBelgium,30510\nNepal,147516\n");
source("automod/com/example/places/CsvDemo.java", """
package com.example.places;
import java.nio.file.*;
import org.example.csvlite.Csv;
public class CsvDemo {
public static void main(String[] args) throws Exception {
for (var row : Csv.parse(Files.readAllLines(Path.of("countries.csv"))))
System.out.println(row.get("Name") + " has area " + row.get("Area"));
System.out.println("Csv is in module " + Csv.class.getModule().getName()
+ ", automatic: " + Csv.class.getModule().getDescriptor().isAutomatic());
}
}
""");
source("automod/module-info.java", "module automod {\n requires org.example.csvlite;\n}\n");
tool("javac", "-p", p("lib2"), "-d", p("mods/automod"),
p("src/automod/module-info.java"), p("src/automod/com/example/places/CsvDemo.java"));
java("-p", mp("mods", "lib2/csvlite-1.10.0.jar"), "-m", "automod/com.example.places.CsvDemo");
System.out.println("-- the same library on the class path: explicit modules cannot read it --");
java("-p", p("mods"), "-cp", p("lib2/csvlite-1.10.0.jar"), "-m", "automod/com.example.places.CsvDemo");
System.out.println("-- class path code lives in the unnamed module --");
source("legacy/Legacy.java", """
import java.lang.reflect.*;
public class Legacy {
public static void main(String[] args) {
System.out.println("named module? " + Legacy.class.getModule().isNamed());
try {
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
System.out.println("deep reflection into java.lang: OK");
} catch (Exception e) {
System.out.println("deep reflection into java.lang: " + e.getClass().getSimpleName());
}
try {
Class<?> vm = Class.forName("jdk.internal.misc.VM");
System.out.println("internal API jdk.internal.misc.VM.isBooted(): " + vm.getMethod("isBooted").invoke(null));
} catch (Exception e) {
System.out.println("internal API jdk.internal.misc.VM: " + e.getClass().getSimpleName());
}
}
}
""");
tool("javac", "-d", p("legacy"), p("src/legacy/Legacy.java"));
java("-cp", p("legacy"), "Legacy");
System.out.println("-- migration flags --");
java("--add-opens", "java.base/java.lang=ALL-UNNAMED",
"--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", "-cp", p("legacy"), "Legacy");
Files.writeString(root.resolve("legacy.options"), """
# options for the legacy app
--add-opens java.base/java.lang=ALL-UNNAMED
--add-exports java.base/jdk.internal.misc=ALL-UNNAMED
""");
java("@" + p("legacy.options"), "-cp", p("legacy"), "Legacy");
try (var walk = Files.walk(root)) { walk.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete()); }
}
}
-- automatic module names --
csvlite-1.9.0.jar -> csvlite (automatic: true, exports [org.example.csvlite])
commons-csv-1.9.0.jar -> commons.csv (automatic: true, exports [org.example.csvlite])
jackson_core-2.17.1.jar -> jackson.core (automatic: true, exports [org.example.csvlite])
my--fancy..lib.jar -> my.fancy.lib (automatic: true, exports [org.example.csvlite])
csvlite-1.10.0.jar with Automatic-Module-Name -> org.example.csvlite
-- an explicit module requiring the automatic module --
$ java -p mods:lib2/csvlite-1.10.0.jar -m automod/com.example.places.CsvDemo
Belgium has area 30510
Nepal has area 147516
Csv is in module org.example.csvlite, automatic: true
-- the same library on the class path: explicit modules cannot read it --
$ java -p mods -cp lib2/csvlite-1.10.0.jar -m automod/com.example.places.CsvDemo
Error occurred during initialization of boot layer
java.lang.module.FindException: Module org.example.csvlite not found, required by automod
-- class path code lives in the unnamed module --
$ java -cp legacy Legacy
named module? false
deep reflection into java.lang: InaccessibleObjectException
internal API jdk.internal.misc.VM: IllegalAccessException
-- migration flags --
$ java --add-opens java.base/java.lang=ALL-UNNAMED --add-exports java.base/jdk.internal.misc=ALL-UNNAMED -cp legacy Legacy
named module? false
deep reflection into java.lang: OK
internal API jdk.internal.misc.VM.isBooted(): true
$ java @legacy.options -cp legacy Legacy
named module? false
deep reflection into java.lang: OK
internal API jdk.internal.misc.VM.isBooted(): true
Common questions
What name does an automatic module get?
The value of Automatic-Module-Name in the JAR's manifest, if present. Otherwise the name comes from the JAR's file name: the version is dropped, and runs of non-alphanumeric characters become dots, so commons-csv-1.9.0.jar becomes commons.csv.
Can my module require a JAR that is on the class path?
No. Named modules can't read the unnamed module. Move the JAR to the module path, where it becomes an automatic module that you can requires.
My old application fails with IllegalAccessError or InaccessibleObjectException on a new JDK. What can I do?
The best fix is to stop using JDK internals, or to update the library that uses them. As a workaround, add --add-exports or --add-opens for the packages named in the error, for example --add-opens java.base/java.lang=ALL-UNNAMED.
Does --illegal-access=permit still work?
No. Java 16 made deny the default, and Java 17 removed the option. Since then the launcher prints a warning and ignores it. Use --add-opens and --add-exports for the specific packages instead.
How do I find out whether a library uses JDK internals?
Run jdeps --jdk-internals library.jar. It lists every use of an internal API and suggests a public replacement where one exists.
API and options reference
| Item | Description |
|---|---|
Automatic-Module-Name: name (JAR manifest) | the module name of a non-modular JAR on the module path |
boolean ModuleDescriptor.isAutomatic() | true for automatic modules |
boolean Module.isNamed() | false for the unnamed module (class-path code) |
--add-exports module/package=target | exports a package to target (a module name or ALL-UNNAMED) |
--add-opens module/package=target | opens a package for deep reflection |
--add-reads module=target, --patch-module module=path | add a readability edge; override classes in a module |
Add-Exports, Add-Opens (manifest of an executable JAR) | the same as the flags, for java -jar |
java @file, javac @file | read options from argument files |
Summary
- A plain JAR on the module path is an automatic module. It reads all modules, exports and opens all packages, and is named by
Automatic-Module-Nameor else by its file name without the version, with separators turned into dots. - Class-path code forms the unnamed module, which reads everything and exposes everything, but explicit modules can never require it. Migration therefore runs bottom-up: platform, then libraries, then the application.
- JDK internals are strongly encapsulated (the
--illegal-accessescape hatch is gone since Java 17).--add-exportsand--add-openswithALL-UNNAMEDkeep legacy code running until it's fixed. @argfileskeep long command lines manageable.
Practice Questions
What module name does the JAR file guava-33.0.0-jre.jar get as an automatic module, assuming no Automatic-Module-Name?
The derivation drops a trailing version that starts with a digit, so -33.0.0-jre is removed and the name is guava. (Guava actually declares Automatic-Module-Name: com.google.common in its manifest, which wins.) Check with jar --describe-module --file guava-33.0.0-jre.jar.
Why can an explicit module require an automatic module but not a JAR on the class path?
An automatic module has a name and is part of the module graph. Class-path JARs belong to the unnamed module, which has no name you could write in requires, and by design explicit modules never read it.
A library on the module path has no module-info.class and depends on a JAR that is still on the class path. Does that work?
Yes. Automatic modules read the unnamed module, so they can use classes from the class path. Explicit modules can't.
An old program on Java 21 fails with InaccessibleObjectException when a library reflects on java.util.ArrayList's private fields. Quick fix?
Start it with --add-opens java.base/java.util=ALL-UNNAMED, or put an Add-Opens attribute in the executable JAR's manifest. The real fix is to upgrade or replace the library so it doesn't depend on JDK internals.
What is the difference between --add-exports and --add-opens?
--add-exports makes the public types of a package accessible, at compile time and runtime. --add-opens permits deep reflection on all members, including private ones, at runtime.
Previous: Modular JARs and Reflective Access in Java: opens and open modules
Next: Java Module Services, requires transitive and static, and Module Tools
Related reading
- Modular JARs and Reflective Access in Java: opens and open modules
- Java Module requires and exports: Dependencies and Exported Packages
- Java Modules Introduction: The Module Concept and a Hello World Module
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values

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.