Sub topic 4
Exporting Packages as the Module's API
Assume you know Java packages, access modifiers, javac, java, JAR files, and the classpath. This chapter focuses on how a module decides which packages other modules may use.
`public` Is Not Enough
In a classpath application, a public class is usually available to any code that can find its package. A named module adds another boundary. A type must satisfy both conditions:
- Its class or member must have suitable Java access, such as
public. - Its package must be exported by the module.
An exported package is part of the module's public API. A package that is not exported remains inaccessible to ordinary code in other named modules, even when it contains public classes.
// src/com.example.greeter/module-info.java
module com.example.greeter {
exports com.example.greeter.api;
}// src/com.example.greeter/com/example/greeter/api/Greeter.java
package com.example.greeter.api;
public class Greeter {
public String greet(String name) {
return "Hello, " + name;
}
}The module exports com.example.greeter.api, so another module may use Greeter. Any package such as com.example.greeter.internal is not exported unless the descriptor lists it.
Exporting Does Not Create a Dependency
exports answers this question: “Which packages can other modules access?”
requires answers a different question: “Which module does this module read?”
A consumer needs both an accessible exported package and a dependency declaration:
// src/com.example.app/module-info.java
module com.example.app {
requires com.example.greeter;
}// src/com.example.app/com/example/app/Main.java
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("modules"));
}
}Compile and run the application from the project directory:
javac -d out --module-source-path src -m com.example.app
java --module-path out -m com.example.app/com.example.app.MainThe compiler checks the module graph. If com.example.greeter does not export com.example.greeter.api, the import fails even though Greeter is public.
The API Boundary
You can export a package only to selected named modules with a qualified export:
module com.example.library {
exports com.example.library.api;
exports com.example.library.internal to com.example.library.tests;
}This is useful for trusted test modules, but it creates tighter coupling. Prefer a normal export for a supported public API and no export for implementation details.
Exercise
A public class is located in com.example.library.internal, but that package is not exported. Can com.example.app import the class after declaring requires com.example.library?
Show answer
No. The package must be exported, and the class must also be accessible according to Java's normal access rules.