7.2 Module Resolution Explained
Module resolution is a critical process in the Java Platform Module System (JPMS) that determines how modules are located, loaded, and linked at runtime. Understanding module resolution is essential for developing modular applications in Java SE 11.
Key Concepts
1. Module Path
The module path is a list of directories and JAR files that the Java runtime uses to locate modules. It replaces the traditional classpath and ensures that only the required modules are loaded, improving performance and security.
Example
java --module-path mods --module com.example.mymodule/com.example.mymodule.Main
2. Module Descriptor
The module descriptor, module-info.java
, is a file that defines a module's name, dependencies, exported packages, and services. It provides the necessary information for the module resolution process.
Example
module com.example.mymodule { requires java.base; exports com.example.mymodule.api; }
3. Module Graph
The module graph is a directed graph that represents the dependencies between modules. Each node in the graph represents a module, and each edge represents a dependency. The module resolution process constructs and traverses this graph to ensure all required modules are available.
Example
Consider three modules: A, B, and C. Module A requires module B, and module B requires module C. The module graph would look like this:
A -> B -> C
4. Resolution Process
The resolution process involves several steps: locating modules on the module path, reading their descriptors, and resolving dependencies. The Java runtime uses the module graph to ensure that all required modules are available and that there are no cyclic dependencies.
Example
When starting a modular application, the Java runtime will:
- Locate the main module on the module path.
- Read the module descriptor to identify dependencies.
- Locate and load each dependency module.
- Repeat the process for each dependency until all required modules are loaded.
5. Automatic Modules
Automatic modules are JAR files that are treated as modules without a module-info.java
file. They can access all other modules on the module path, making it easier to migrate legacy code to the module system.
Example
java --module-path lib/mylibrary.jar --module com.example.mymodule/com.example.mymodule.Main
Examples and Analogies
Think of module resolution as a library catalog system. When you need a book (module), you first check the catalog (module path) to find its location. The catalog entry (module descriptor) tells you what other books (dependencies) you need to find. You then follow the references (module graph) to locate all required books, ensuring there are no missing or circular references.
By mastering module resolution, you can ensure that your Java SE 11 applications are modular, maintainable, and free from dependency issues, making them easier to develop and deploy.