Java 9 如何避免拆分包

How split packages are avoided in Java 9

我是 Java 9 的新手,正在浏览 YouTube 上 Java 的模块化视频讲座。 他们提到了模块化的 3 个好处—— 1.没有缺失的依赖 2.无循环依赖 3. 没有拆分包。

据我了解,关于拆分包,假设一个应用程序依赖于多个依赖项,并且假设包 abc.pqr.xyz 存在于 1 个以上的 jar 中。 然后有可能该包中的一些 classes 将被 jar1 使用,而其他 classes 来自 jar2。 这可能会导致运行时出现一些难以调试的问题。

视频说模块化解决了这个问题。 但这就是我想了解的内容吗?

假设有 test.module1 有以下模块信息 -

module test.module1{
exports abc.pqr.xyz;
}

具有以下模块信息的另一个模块 2-

module test.module2{
 exports abc.pqr.xyz;
}

现在假设我在我的应用程序中添加了这两个模块的依赖项-

module test.myapp{
 requires test.module1;
 requires test.module2;
}

现在我又有 2 个模块依赖项,其中一些 classes 可能会出现在这两个模块中。 那么在运行时如何解析从哪个模块获取 class 定义? Java 9 如何避免拆分包的问题?

Java 模块系统通过在 JVM 启动时拒绝这种情况来解决拆分包问题。当 JVM 启动时,它会立即开始解析模块图,当它在 test.myapp 的模块路径中遇到两个模块时,JVM 会抛出一个错误,指示 test.module1test.module2 正在尝试导出相同的包。

对于问题中描述的场景,您将开始面临错误阅读:

Module test.myapp reads package from both test.module1 and test.module2

来自 The State of the Module System 的模块的

Readability 详细说明了模块的使用,您的用例应该会感兴趣(强调我的):

The readability relationships defined in a module graph are the basis of reliable configuration: The module system ensures

  • that every dependence is fulfilled by precisely one other module
  • that the module graph is acyclic
  • that every module reads at most one module defining a given package
  • and that modules defining identically-named packages do not interfere with each other.

在模块系统中暗示相同的好处也很详细

Reliable configuration is not just more reliable; it can also be faster. When code in a module refers to a type in a package then that package is guaranteed to be defined either in that module or in precisely one of the modules read by that module.

When looking for the definition of a specific type there is, therefore, no need to search for it in multiple modules or, worse, along the entire class path.


也就是说,您的实施的当前解决方案是

  • 如果模块test.module1test.module2显式模块,您可以选择实现包abc.pqr.xyz 其中之一 或者你将它从两者中拉出到你自己的一个单独的模块 test.mergeModule 中,此后可以作为一个独立的模块在其客户端中使用。

  • 如果这些(或其中任何一个)是自动模块,您可以使用bridge extended to the classpath and let such jar remain on the classpath and be treated as the unnamed module, which shall by default export all of its packages. At the same time, any automatic module while reading every other named module is also made to read the unnamed module

    再次引用文档并举例说明,以便您可以关联到您的问题:

    If code in the explicit module com.foo.app refers to a public type in com.foo.bar, e.g., and the signature of that type refers to a type in one of the JAR files still on the class path, then the code in com.foo.app will not be able to access that type since com.foo.app cannot depend upon the unnamed module.

    This can be remedied by treating com.foo.app as an automatic module temporarily, so that its code can access types from the class path, until such time as the relevant JAR file on the class path can be treated as an automatic module or converted into an explicit module.