模块系统 (Java 9+)
概述
Java 9 引入了模块系统(Project Jigsaw),旨在提高代码的可维护性、安全性和可扩展性。模块系统允许开发者将代码组织成模块,每个模块可以有自己的依赖关系和访问控制。
模块的基本概念
1. 模块声明
模块通过 module-info.java 文件进行声明。这个文件位于模块的根目录下,定义了模块的名称、依赖关系、导出的包和服务的提供与使用。
module com.example.mymodule {
requires java.base; // 依赖于 java.base 模块
exports com.example.mymodule.api; // 导出 api 包
}
2. 模块路径
模块路径(Module Path)是用于指定模块的位置。与类路径(Class Path)不同,模块路径只包含模块化的代码。
java --module-path mods --module com.example.mymodule/com.example.mymodule.Main
3. 模块依赖
模块可以声明对其他模块的依赖。依赖关系通过 requires 关键字声明。
module com.example.mymodule {
requires java.base;
requires com.example.anothermodule;
}
4. 模块导出
模块可以导出包,使得其他模块可以访问这些包中的公共类型。
module com.example.mymodule {
exports com.example.mymodule.api;
}
5. 模块服务
模块可以提供和使用服务。服务提供者通过 provides 关键字声明,服务使用者通过 uses 关键字声明。
module com.example.mymodule {
provides com.example.mymodule.api.Service with com.example.mymodule.impl.ServiceImpl;
}
module com.example.anothermodule {
uses com.example.mymodule.api.Service;
}
代码示例
1. 创建一个简单的模块
首先,创建一个名为 com.example.mymodule 的模块。
module-info.java
module com.example.mymodule {
exports com.example.mymodule.api;
}
com/example/mymodule/api/HelloWorld.java
package com.example.mymodule.api;
public class HelloWorld {
public void sayHello() {
System.out.println("Hello, World!");
}
}
2. 使用模块
创建另一个模块 com.example.anothermodule,并使用 com.example.mymodule 模块。
module-info.java
module com.example.anothermodule {
requires com.example.mymodule;
}
com/example/anothermodule/Main.java
package com.example.anothermodule;
import com.example.mymodule.api.HelloWorld;
public class Main {
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.sayHello();
}
}
3. 编译和运行
编译模块:
javac --module-path mods -d mods/com.example.mymodule src/com.example.mymodule/module-info.java src/com.example.mymodule/com/example/mymodule/api/HelloWorld.java
javac --module-path mods -d mods/com.example.anothermodule src/com.example.anothermodule/module-info.java src/com.example.anothermodule/com/example/anothermodule/Main.java
运行模块:
java --module-path mods --module com.example.anothermodule/com.example.anothermodule.Main
实践练习
练习 1: 创建一个模块并导出包
- 创建一个名为
com.example.math的模块。 - 在模块中创建一个包
com.example.math.operations,并定义一个类Calculator,包含加法和减法方法。 - 在
module-info.java中导出com.example.math.operations包。
练习 2: 使用模块
- 创建另一个名为
com.example.app的模块。 - 在
com.example.app模块中使用com.example.math模块的Calculator类。 - 编写一个
Main类,调用Calculator类的加法和减法方法。
练习 3: 模块服务
- 在
com.example.math模块中定义一个接口MathService,并提供一个实现类MathServiceImpl。 - 在
com.example.math模块的module-info.java中使用provides关键字声明服务提供者。 - 在
com.example.app模块中使用MathService服务。
总结
Java 9 引入的模块系统为 Java 应用程序提供了更好的组织和封装方式。通过模块系统,开发者可以更好地管理依赖关系、控制访问权限,并提高代码的可维护性和安全性。通过本教程的学习,你应该能够创建和使用简单的 Java 模块,并理解模块系统的基本概念和用法。