Module
Java introduced the module system in Java 9 through the Java Platform Module System (JPMS). This system allows developers to create modular applications, which can lead to better application structuring, reduced JAR hell, and enhanced security.
Here's a basic tutorial on Java modules:
Understanding Modules:
A module is a collection of Java classes, resources, and configurations, packaged together. Each module has a unique name and can explicitly specify its dependencies (other modules it requires) and what it exports for other modules to use.
Setting Up:
Create two new directories to demonstrate a simple modular application:
com.greetings
(Our custom module)mods
(Where compiled modules will reside)
Writing the Module Descriptor:
Inside the com.greetings directory, create a new directory called src.
Under src, create another directory structure com/greetings. Here's how it looks:
com.greetings/
│
└───src/
│
└───com/greetings/
Now, inside com/greetings, create a file named module-info.java. This is the module descriptor:
module com.greetings {
exports com.greetings;
}
This specifies a module named com.greetings that exports the com.greetings package.
Writing the Main Class:
Still inside the com/greetings directory (where your module-info.java resides), create a file named Main.java:
package com.greetings;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, Modules!");
}
}
Compiling the Module:
Navigate to the root directory where com.greetings resides and run the following:
$ javac -d mods/com.greetings com.greetings/src/com/greetings/module-info.java com.greetings/src/com/greetings/Main.java
This command compiles the module and puts the output in the mods/com.greetings directory.
Running the Modular Application:
$ java --module-path mods -m com.greetings/com.greetings.Main
You should see the output Hello, Modules!.
Key Concepts:
- Module Descriptor: Every module requires a module-info.java which describes its dependencies and exports.
- exports: This keyword allows the specified package to be accessible from outside the module.
- requires: If your module depends on another module, you'll use this keyword in your module descriptor.
- --module-path: This replaces the traditional classpath. It specifies where the compiled modules reside.
Advantages:
- Encapsulation: Internal packages can be hidden from external use.
- Clear Dependencies: Clearly specified dependencies in the module-info.java file.
- Improved Performance: The JVM can optimize better due to clear module boundaries and dependencies.