草庐IT

Java 9 : Possible to have 2 modules with same name on module path

coder 2024-03-06 原文

是否可以在模块路径上有 2 个名称完全相同(但内容略有不同)的模块?

据我所知,Java 9 编译器并没有提示它。我有 2 个模块声明如下:

module com.dj.helper {
    exports com.dj.helper;
}

两者都包含 com.dj.helper 包,但包内的内容不同。然后在我的主应用程序中,我希望导入此模块:

module com.dj {
    requires com.dj.helper;
}

同名的两个模块都在我的模块路径上。

我希望在编译我的 com.dj 模块时,编译器会提示同一模块存在两次,但事实并非如此。这是否实际上意味着您的模块路径上可能有同一个 jar 的 2 个版本,而 Java 不知道要使用哪一个?

最佳答案

没有

在模块路径的同一个目录下不可能有两个同名的模块。官方文件并没有把这些信息放在特别显眼的地方——它是the Javadoc of ModuleFinder::of。放弃它:

It is an error if a directory contains more than one module with the same name.

我创建了 a small demo project for the module systemit covers that case通过创建同一模块的两个版本...

jar --create
    --file mods/monitor.observer.beta-1.0.jar
    --module-version 1.0
    -C classes/monitor.observer.beta .
jar --create
    --file mods/monitor.observer.beta-2.0.jar
    --module-version 2.0
    -C classes/monitor.observer.beta .

...然后在下次编译时引用该文件夹...

javac
    --module-path mods
    -d classes/monitor.statistics
    $(find monitor.statistics -name '*.java')

...正如预期的那样会导致以下错误消息:

error: duplicate module on application module path
module in monitor.observer.beta
1 error

请注意,我说的是在同一目录中。跨目录多个模块是可能的。

模块系统只在 目录中强制执行唯一性。再次来自ModuleFinder::of (强调我的):

The module finder locates modules by searching each directory, exploded module, or packaged module in array index order. It finds the first occurrence of a module with a given name and ignores other modules of that name that appear later in the sequence.

这使得在不同目录中拥有相同的模块成为可能。

关于Java 9 : Possible to have 2 modules with same name on module path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573572/

有关Java 9 : Possible to have 2 modules with same name on module path的更多相关文章

随机推荐