Sub topic 1
Why Modules: The Problems with the Classpath
Prerequisites
This chapter assumes you understand Java packages, access modifiers, javac, java, JAR files, and the classpath. You should also know that a Java interface defines operations that a class can implement.
Why modules: the problems with the classpath
The classpath is a list of directories and JAR files that the compiler and runtime search for classes. Every classpath entry is broadly visible to every other entry. This makes small applications simple, but large applications harder to control.
Common problems include:
- Two JAR files contain the same class. The result depends on classpath order.
- A library exposes implementation packages even when applications should use only its public API.
- A program starts successfully but fails later because a required JAR is missing.
- Dependencies are difficult to describe. A JAR may use another JAR without declaring that relationship.
- Internal classes can be accessed accidentally, creating tight coupling.
The Java Platform Module System (JPMS) gives applications named modules. A module declares its dependencies and the packages it makes accessible.
Your first module and `module-info.java`
A module descriptor is a file named module-info.java at the module's source root. It names the module and describes its boundary.
// 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 name is com.example.greeter. The exports directive makes com.example.greeter.api available to other modules. Packages that are not exported remain internal.
Declaring dependencies with `requires`
A module uses requires to declare that it depends on another named module.
// src/com.example.app/module-info.java
module com.example.app {
requires com.example.greeter;
}Code in com.example.app can now import exported types from com.example.greeter. The dependency is checked during compilation and when the application starts.
Readability and the module graph
The module system builds a directed graph. Each requires edge means that the requiring module can read the required module. Reading is necessary, but it does not override exports: the package must also be exported.
The compiler and runtime use this graph to reject missing dependencies and illegal access earlier than a classpath-based application often can.
Exercise
If com.example.app requires com.example.greeter, but the greeter module does not export com.example.greeter.internal, can the app import a public class from that package?
Show answer
No. The app can read the module, but it cannot access a package that the module does not export.