7.2.2 Named Modules Explained
Named modules are a fundamental concept in the Java Platform Module System (JPMS). They provide a way to encapsulate related packages, classes, and resources into a single, self-contained unit. Named modules are explicitly defined with a module-info.java
file, which specifies their dependencies, exports, and other configurations.
Key Concepts
1. Module Definition
A named module is defined by creating a module-info.java
file in the root directory of the module. This file contains declarations that specify the module's name, its dependencies, and the packages it exports.
Example
module com.example.mymodule { requires java.base; exports com.example.mymodule.api; }
2. Module Dependencies
Named modules can depend on other modules using the requires
clause in the module-info.java
file. This ensures that the required modules are available at runtime, preventing runtime errors due to missing dependencies.
Example
module com.example.mymodule { requires java.base; requires java.logging; }
3. Module Exports
The exports
clause in the module-info.java
file specifies which packages are accessible to other modules. This encapsulation helps in maintaining the integrity and security of the module's internal implementation.
Example
module com.example.mymodule { exports com.example.mymodule.api; }
4. Module Path
The module path is a list of directories or JAR files that the Java runtime searches for modules. It is specified using the --module-path
or -p
option when running Java applications. The module path ensures that all required modules are available and can be loaded at runtime.
Example
java --module-path mods -m com.example.mymodule/com.example.mymodule.Main
5. Strong Encapsulation
Named modules provide strong encapsulation, meaning that only explicitly exported packages can be accessed by other modules. This helps in preventing unintended dependencies and improves the maintainability of the codebase.
Example
module com.example.mymodule { exports com.example.mymodule.api; // com.example.mymodule.internal is not exported }
Examples and Analogies
Think of named modules as self-contained toolboxes. Each toolbox (module) has a label (module-info.java) that describes what tools (packages and classes) are inside and what other toolboxes it depends on. The module path is like a shelf where all the toolboxes are stored, and the Java runtime knows exactly which toolbox to pick up based on the project requirements.
By mastering named modules, you can build scalable and maintainable Java SE 11 applications, ensuring that your code is organized, secure, and optimized for performance.