14.2.2 Named Modules Explained
Named modules are a fundamental concept in the Java Platform Module System (JPMS), introduced in Java 9. They provide a way to encapsulate code and manage dependencies explicitly, making large-scale applications more maintainable and secure.
Key Concepts
1. Module Declaration
Named modules are defined using a module-info.java
file located in the root directory of the module. This file specifies 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 Name
The module name is a unique identifier that follows the Java package naming conventions. It is used to reference the module in other parts of the application and in the module path.
Example
module com.example.mymodule { // Module declaration }
3. Requires Directive
The requires
directive is used to declare dependencies on other modules. It specifies that the current module depends on the functionality provided by another module. The java.base
module is implicitly required by all modules.
Example
module com.example.mymodule { requires java.base; requires com.example.anothermodule; }
4. Exports Directive
The exports
directive is used to make packages within the module accessible to other modules. Only the exported packages are visible to other modules, ensuring encapsulation and security.
Example
module com.example.mymodule { exports com.example.mymodule.api; }
5. Opens Directive
The opens
directive is used to allow reflective access to packages within the module. This is particularly useful for frameworks that rely on reflection, such as Spring or Hibernate.
Example
module com.example.mymodule { opens com.example.mymodule.internal; }
Examples and Analogies
Think of named modules as self-contained units of functionality, similar to departments in a large organization. Each department (module) has its own responsibilities and dependencies, and it only exposes its APIs to other departments (modules) when necessary. This ensures that each department can operate independently while still collaborating with others.
For instance, in a large e-commerce application, you might have modules for user management, product catalog, and payment processing. Each module encapsulates its functionality and only exposes the necessary APIs to other modules. This modular approach makes the application easier to manage, test, and extend.
By mastering named modules, you can create more organized, maintainable, and scalable Java applications, making it easier to manage complex projects and collaborate with other developers.