Sub topic 13
The unnamed module and classpath code
Prerequisites and the migration boundary
Assume you know Java packages, access modifiers, javac, java, JAR files, and the basic idea of reflection. This chapter focuses on how classpath code interacts with named modules.
The unnamed module is the module that contains classes loaded from the classpath. You do not write a module-info.java file for it. A classpath application, or a legacy JAR placed on the classpath, runs in this module.
The unnamed module has special migration-friendly rules:
- It reads every named module.
- Its packages are exported and open.
- It can use public types from exported packages of named modules.
- Named modules do not automatically read it.
This one-way relationship lets older classpath applications call modular libraries, while modular applications cannot freely depend on legacy classpath libraries.
A classpath application using a named module
Suppose a library is compiled as the named module com.example.greeter:
module com.example.greeter {
exports com.example.greeter.api;
}A classpath application can use the exported package without declaring requires:
package com.example.app;
import com.example.greeter.api.Greeter;
public class Main {
public static void main(String[] args) {
System.out.println(new Greeter().greet("classpath"));
}
}Compile and run the application with the library on the module path:
javac --module-path mods -d classes src/com/example/app/Main.java
java --module-path mods --class-path classes com.example.app.MainThe application is in the unnamed module. It can read com.example.greeter, but it still cannot use a non-exported package such as com.example.greeter.internal.
A named module using a legacy JAR
Now reverse the arrangement. If legacy.jar is on the classpath, its classes belong to the unnamed module. A named application module cannot import those classes by default because it does not read the unnamed module.
You can temporarily add that edge with --add-reads:
javac --module-path mods --add-reads com.example.app=ALL-UNNAMED \
-d out --module-source-path src -m com.example.app
java --module-path mods --class-path legacy.jar \
--add-reads com.example.app=ALL-UNNAMED \
-m com.example.app/com.example.app.MainThis is a migration aid, not a replacement for a proper module dependency. Prefer putting the legacy JAR on the module path as an automatic module when its package structure permits, or migrate it to a named module.
| Code location | Module kind | Can read named modules by default? | Can named modules read it by default? |
|---|---|---|---|
| Classpath classes | Unnamed | Yes | No |
| `module-info.java` application | Named | Only with `requires` | Yes, when required |
Exercise
Why can a classpath application use an exported package from a named module without writing requires?
Show answer
The classpath application belongs to the unnamed module, and the unnamed module reads every named module automatically.