Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java 9 Module System

Java 9 Module System

Java 9 New Features Java 9 New Features

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 module's code is organized into multiple packages, each containing Java classes and interfaces; the module's data includes resource files and other static information.

An important feature of Java 9 modules is that the root directory of the artifact contains a module-info.class file describing the module. The artifact format can be a traditional JAR file or the new JMOD file introduced in Java 9. This file is compiled from the source file module-info.java in the root directory. This module declaration file can describe the different characteristics of the module.

In the module-info.java file, we can declare a module with the new keyword module, as shown below. The most basic module declaration for a module named com.mycompany.mymodule is given below.

module com.runoob.mymodule {
}

Creating a module

Next we create a module called com.runoob.greetings.

Step 1

Create the folder C:>JAVA\src, then create a folder com.runoob.greetings with the same name as the module inside that directory.

Step 2

Create the module-info.java file in the C:>JAVA\src\com.runoob.greetings directory, with the following code:

module com.runoob.greetings { }

module-info.java is used to create a module. In this step we created the com.runoob.greetings module.

Step 3

Add the source code file to the module: create the file Java9Tester.java in the directory C:>JAVA\src\com.runoob.greetings\com\runoob\greetings, with the following code:

package com.runoob.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.runoob.greetings folder inside it, and compile the module into this directory:

C:/>JAVA> javac -d mods/com.runoob.greetings 
   src/com.runoob.greetings/module-info.java 
   src/com.runoob.greetings/com/runoob/greetings/Java9Tester.java

Step 5

Run the module and check the output:

C:/>JAVA> java --module-path mods -m com.runoob.greetings/com.runoob.greetings.Java9Tester
Hello World!

module-path specifies the path where the module is located.

-m specifies the main module.

Java 9 New Features Java 9 New Features