Module là gói mã và dữ liệu. Mã của module được tổ chức thành nhiều package và mỗi package chứa các class và interface Java. Dữ liệu của module bao gồm file tài nguyên và thông tin tĩnh khác. Đặc điểm quan trọng của module là chứa file "module-info.class" mô tả module trong thư mục gốc của artifact. Định dạng artifact có thể là file JAR truyền thống hoặc file JMOD. File này được biên dịch từ file nguồn module-info.java trong thư mục gốc.
Chúng ta khai báo module trong file module-info.java với từ khóa mới module. Khai báo cơ bản cho module com.company.mymodule như sau:
module com.tutorialspoint.mymodule { }
Các bước tạo Module:
Bước 1:
Tạo thư mục C:\JAVA\src rồi tạo thư mục com.tutorialspoint.greetings trùng tên module.
Bước 2:
Tạo file module-info.java trong C:\JAVA\src\com.tutorialspoint.greetings với nội dung:
module com.tutorialspoint.greetings { }
Bước 3:
Thêm file mã nguồn vào module, tạo file JavaTest.java trong thư mục C:\JAVA\src\com.tutorialspoint.greetings\com\tutorialspoint\greetings:
package com.tutorialspoint.greetings;
public class JavaTest {
public static void main(String args[]) {
System.out.println("Hello Tutorialspoint!");
}
}
Bước 4:
Tạo thư mục C:\JAVA\mods, tạo thư mục com.tutorialspoint.greetings trong đó, sau đó biên dịch module vào thư mục này:
C:\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/module-info.java C:\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/JavaTest.java
Bước 5:
Thực thi module và xem kết quả:
C:\JAVA>java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.JavaTest Hello Tutorialspoint!
Trong đó, module-path chỉ định đường dẫn module và -m chỉ định module chính (main module).