Java 9 中模組資訊檔案(module-info 檔案)中的“requires”子句有什麼作用?
**模組**是 **Java 9** 中引入的一個重要概念。透過使用這個概念,我們可以將程式碼劃分為稱為 **模組** 的更小的元件。因此,每個模組都有其自身的職責,並宣告其對其他模組的依賴關係以正常工作。為了宣告一個模組,我們需要將“**module-info.java**”檔案包含到根原始碼中。
"**module-info**" 檔案中有一些型別的“**requires**”子句
1) requires <module>: 預設情況下,模組不知道 **module-path** 中存在的其他模組。因此,每次我們想要訪問另一個模組時,都需要在我們的 module-info.java 中新增一行:“**requires**”。
module com.tutorialspoint.gui {
requires com.tutorialspoint.model;
requires java.desktop;
}2) requires transitive <module>: 在我們的模組“**com.tutorialspoint.model**”的情況下:返回模組“**com.core**”匯出的介面型別。因此,任何想要使用它們的模組也需要“**com.core**”來訪問此第二個模組的類,而不會出現編譯錯誤。**Java 9** 允許使用關鍵字“**transitive**”來指示透過傳遞性。使用者“**com.tutorialspoint.model**”能夠訪問“**com.core**”,從而可以輕鬆進行實現更改。
module com.tutorialspoint.model {
requires transitive com.core;
}3) requires static <module>: 關鍵字“**requires static**”表示可選依賴的概念,例如,該模組是
- 編譯時強制性:如果模組在編譯時的模組路徑中不存在,則可能會引發編譯錯誤。
- 執行時可選:在應用程式啟動時,在完整性檢查階段不會考慮該模組。即使模組不存在,應用程式也會啟動。
例如,我們希望建議將應用程式的資料持久化到 **Oracle 資料庫** 或 **H2 資料庫** 中。
module com.tutorialspoint.model {
requires static ojdbc
requires static h2daabase.h2;
}廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP