7.2.1 Automatic Modules Explained
Automatic Modules are a feature introduced in Java 9 to facilitate the migration of existing JAR files into the Java Platform Module System (JPMS). They allow legacy code to be integrated into a modular environment without requiring any modifications to the original JAR files. This makes it easier to transition to the modular system while maintaining compatibility with existing codebases.
Key Concepts
1. Automatic Module Creation
An automatic module is created simply by placing an existing JAR file on the module path. The Java runtime automatically treats this JAR as a module, deriving its name from the JAR filename. This allows the JAR to be used in a modular environment without needing a module-info.java
file.
Example
java --module-path lib/mylibrary.jar --module com.example.mymodule/com.example.mymodule.Main
2. Module Name Derivation
The name of an automatic module is derived from the JAR filename. The filename is converted to a valid module name by replacing hyphens with dots and removing the file extension. For example, a JAR named my-library-1.0.jar
would be treated as an automatic module named my.library
.
Example
my-library-1.0.jar -> my.library
3. Automatic Module Behavior
Automatic modules have specific behaviors that differ from named modules. They automatically export all their packages, allowing other modules to access their public types. Additionally, they can read all other modules on the module path, including both named and automatic modules.
Example
module com.example.mymodule { requires my.library; // Automatic module derived from my-library-1.0.jar }
4. Migration Benefits
Automatic modules provide a smooth transition path for migrating legacy code to the modular system. They allow developers to gradually modularize their applications by first integrating existing JAR files as automatic modules and then refactoring them into named modules as needed.
Example
Consider a legacy application that uses a third-party library. By placing the library JAR on the module path, the application can start benefiting from modularity without requiring any changes to the library itself.
Examples and Analogies
Think of automatic modules as adapters that allow old devices to work with new systems. For example, if you have an old camera that uses a specific memory card, an adapter can make it compatible with a new computer. Similarly, automatic modules make existing JAR files compatible with the new modular system, allowing them to be used seamlessly without requiring any modifications.
By understanding automatic modules, you can effectively integrate legacy code into modern modular applications, ensuring a smooth transition to the Java Platform Module System.