Sub topic 5
Readability and the Module Graph
Assume you know Java packages, access modifiers, javac, java, and the classpath. This chapter uses readability to mean one module is allowed to read the types exposed by another module.
A directed graph of modules
A modular application is a module graph. Each module is a node. Each requires directive creates a directed edge from the requiring module to the required module.
If module com.example.app declares requires com.example.greeter, then com.example.app reads com.example.greeter. The app can use packages that the greeter module exports.
// src/com.example.greeter/module-info.java
module com.example.greeter {
exports com.example.greeter.api;
}
// src/com.example.app/module-info.java
module com.example.app {
requires com.example.greeter;
}The edge controls readability, but it does not expose every type in the target module. The target package must also be exported. A public class in a non-exported package remains inaccessible to other modules.
Resolving the graph
At compile time, the compiler checks that every required module can be found and that referenced packages are readable and exported. At launch, the Java runtime resolves the same graph on the module path.
javac -d out --module-source-path src -m com.example.app
java --module-path out -m com.example.app/com.example.app.MainThe runtime starts with the requested root module, com.example.app, then follows its requires edges. Required modules are resolved into the graph. If a required module is missing, startup fails instead of silently searching unrelated classpath entries.
Every named module implicitly reads java.base, which contains packages such as java.lang and java.util. You therefore do not write requires java.base.
Transitive readability
Normally, readability is not passed through dependencies. Suppose app requires library, and library requires database. The app does not automatically read database.
Use requires transitive when a dependency appears in your public API and clients need to use that dependency’s types:
module com.example.library {
requires transitive com.example.database;
}This gives direct readers of com.example.library implied readability of com.example.database. Use it carefully because it expands the API contract and couples clients to another module.
Exercise
Module A requires module B. Module B exports package p but does not declare its dependency on module C as transitive. Can A directly use an exported package from C?
Show answer
No. A must declare its own requires C, unless B changes its declaration to requires transitive C.