如何在 Java 9 中创建模块?
模块是代码和数据的包。模块的代码被组织成多个 包 ,每个包包含 java 类 和接口。模块的数据包括资源 文件 和其他静态 信息。模块的一个重要特性是它在其工件的根目录中包含描述模块的"module-info.class"文件。工件格式可以是传统的JAR 文件或JMOD 文件。此文件由根目录中的源代码文件 module-info.java 编译而成。
我们可以在 module-info.java 文件中使用 new 关键字 module 声明一个模块,模块 com.company.mymodule 的基本模块声明如下所示。
module com.tutorialspoint.mymodule {
创建模块的步骤:
第一步:
创建一个文件夹 C:\JAVA\src,然后创建一个与模块同名的文件夹 com.tutorialspoint.greetings。
第二步:
在 module-info.java 文件中创建C:\JAVA\src\com.tutorialspoint.greetings目录下,代码如下。
module com.tutorialspoint.greetings {
第三步:
给模块添加源代码文件,在C:\JAVA\src\com.tutorialspoint.greetings\com\tutorialspoint\greetings目录下创建文件JavaTest.java,代码如下:
package com.tutorialspoint.greetings;
public class JavaTest {
public static void main(String args[]) {
System.out.println("Hello Tutorialspoint!");
}
第四步:
创建文件夹C:\JAVA\mods,然后在该目录下创建com.tutorialspoint.greetings文件夹,并将模块编译到该目录下。
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
第五步:
执行模块,查看输出结果
C:\JAVA>java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.JavaTest Hello Tutorialspoint!
在上面的代码中,module-path指定模块所在的路径,-m 指定主模块。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

