Java 模块化开发
warning:
这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
在Java中实现模块化开发,可以使用Java Platform Module System (JPMS),它是在JDK 9及以后版本中引入的。以下是一个简单的例子,展示如何定义一个模块和引入模块依赖。
- 创建一个名为
module-info.java的文件,定义模块:
module com.example.mainmodule {
requires java.base; // 引入Java的基础模块
requires com.example.another; // 引入另一个自定义模块
// 导出模块内部的包供其他模块使用
exports com.example.mainmodule;
}- 在另一个模块中,比如
another-module,创建一个module-info.java文件:
module com.example.another {
requires java.base;
// 定义模块内部的包
exports com.example.another;
}- 在
com.example.mainmodule中的某个类中使用com.example.another模块中的类:
// 在com.example.mainmodule中的SomeClass.java
package com.example.mainmodule;
public class SomeClass {
public static void main(String[] args) {
// 使用另一个模块中的类
com.example.another.AnotherClass.doSomething();
}
}在com.example.another模块中的另一个类:
// 在com.example.another中的AnotherClass.java
package com.example.another;
public class AnotherClass {
public static void doSomething() {
System.out.println("Doing something in another module");
}
}确保在编译时,模块路径被正确设置,并且模块能够被找到。使用javac和java命令时,可以通过--module-path指定模块所在的目录。例如:
javac --module-source-path src --module-path lib -d out src/com.example.mainmodule/module-info.java src/com.example.mainmodule/com/example/mainmodule/SomeClass.java
java --module-path out:lib -m com.example.mainmodule/com.example.mainmodule.SomeClass在这个例子中,src是源代码目录,out是编译输出目录,lib是模块依赖存放的目录。源代码被编译到out目录,然后运行模块com.example.mainmodule中的主类SomeClass。
评论已关闭