Module là đơn vị code độc lập: tập hợp package, tài nguyên tĩnh (file properties...). Module Descriptor (file module-info.java tại root module) là "hộ chiếu" của module – khai báo tên, phụ thuộc, xuất khẩu package, dịch vụ...
Ví dụ module-info.java
module com.myproject.module1 {
requires com.myproject.module2;
exports com.myproject.project1;
exports com.myproject.project2;
}
Các chỉ thị (directives) chính
| Chỉ thị | Cú pháp | Ý nghĩa |
|---|---|---|
| module | module name { ... } | Khai báo tên module (duy nhất). |
| requires | requires module.name; | Phụ thuộc module khác (đọc public types được export). |
| requires transitive | requires transitive module.name; | Module phụ thuộc này tự động được truyền cho module đọc module hiện tại. |
| exports | exports pkg.name; | Xuất khẩu package công khai cho mọi module requires. |
| exports ... to | exports pkg.name to module.name; | Xuất khẩu riêng cho module cụ thể (qualified export). |
| uses | uses class.name; | Khai báo tiêu thụ service (ServiceLoader). |
| provides ... with | provides class.name with class.name.impl; | Đăng ký triển khai service. |
| opens | opens pkg.name; | Mở package cho reflection truy cập private (deep reflection). |
| opens ... to | opens pkg.name to module.name; | Mở package cho reflection chỉ cho module cụ thể. |
Lợi ích
- Strong encapsulation: Package không export thì không truy cập được từ bên ngoài (da cả reflection trừ khi opens).
- Reliable configuration: Phụ thuộc rõ ràng, phát hiện thiếu module ở compile-time.
- Scalable: Tạo runtime nhỏ gọn cho thiết bị nhúng.
Module Descriptor là trái tim của Java Platform Module System (JPMS) – Jigsaw Project.