โมดูลเป็นหน่วยอิสระของแอปพลิเคชันแทนฟังก์ชันเดียว โมดูลประกอบด้วย 3 คอมโพเนนต์สำคัญ
- Name: ระบุตัวตนอย่างเดียว
- Dependencies: โมดูลอื่นที่พึ่งพา
- Exported packages: แพ็กเกจที่เปิดให้แอปพลิเคชันภายนอกใช้
เพื่อประกาศโมดูล ต้องเพิ่มไฟล์ module-info.java ที่ root ของ source code คอมโพเนนต์ในไฟล์นี้ประกอบด้วย name requires exports และ exports to
เทมเพลต module-info.java
module <module-name> {
requires <module-name1>;
requires <module-name2>;
...
exports <package-name1>;
exports <package-name2>;
...
exports <package-name> to <module-name>;
}
คำอธิบายแต่ละส่วน
- Name: ลักษณะสำคัญของโมดูล ระบบโมดูลระบุโมดูลด้วยชื่อ จึงต้อง unique
- requires: ใช้กำหนด dependencies และ external modules ที่โมดูลปัจจุบันพึ่งพา ต้องมี entry "requires" แยกต่างหากสำหรับแต่ละโมดูลที่พึ่งพา Java 9 มี base module เป็นโมดูลอิสระไม่พึ่งพาอื่น มีให้ by default ไม่ต้องระบุ requires
- exports: ใช้กำหนดแพ็กเกจของโมดูลปัจจุบันที่ export เปิดให้โมดูลอื่นใช้ ต้องมี entry "exports" แยกต่างหากสำหรับแต่ละแพ็กเกจ
- exports to: export แพ็กเกจเฉพาะโมดูลที่ระบุ แทนที่จะ export ให้ทุกโมดูล
ตัวอย่างจริง
module com.tutorialspoint.app {
/** Modules upon which this module depends */
requires com.tutorialspoint.services;
/** Packages exposed by this module */
exports com.tutorialspoint.app.util;
exports com.tutorialspoint.app.model to com.tutorialspoint.services;
}