Java 9 Module System
One of the biggest changes in Java 9 is the introduction of the module system (Project Jigsaw).
A module is an encapsulation of code and data. The code of a module is organized into multiple packages, each containing Java classes and interfaces; the data of a module includes resource files and other static information.
An important feature of the Java 9 module is that it contains a module-info.class file describing the module in the root directory of its artifact. The artifact can be in the traditional JAR file format or the JMOD file format newly added in Java 9. This file is compiled from the source code file module-info.java in the root directory. The module declaration file can describe different characteristics of the module.
In the module-info.java file, we can use the new keyword module to declare a module, as shown below. The following shows the most basic module declaration for a module com.mycompany.mymodule.
module com.example.mymodule {
}
Creating a Module
Next, let's create acom.example.greetingsmodule.
Step 1
Create the folder C:\>JAVA\src, then create a folder com.example.greetings with the same name as the module in that directory.
Step 2
Create the module-info.java file in the C:\>JAVA\src\com.example.greetings directory, with the code as follows:
module com.example.greetings { }
module-info.java is used to create a module. In this step, we created the com.example.greetings module.
Step 3
Add a source code file to the module. Create the file Java9Tester.java in the directory C:\>JAVA\src\com.example.greetings\com\example\greetings, with the code as follows:
package com.example.greetings;
public class Java9Tester {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Step 4
Create the folder C:\>JAVA\mods, then create the com.example.greetings folder in that directory, and compile the module to this directory:
C:/>JAVA> javac -d mods/com.example.greetings src/com.example.greetings/module-info.java src/com.example.greetings/com/example/greetings/Java9Tester.java
Step 5
Execute the module and view the output:
C:/>JAVA> java --module-path mods -m com.example.greetings/com.example.greetings.Java9Tester Hello World!
module-pathSpecifies the path where the module is located.
-mSpecifies the main module.
Other Extensions
Java 9 New Features