gpt4 book ai didi

java - 为什么我们在java-9模块系统中需要require static?

转载 作者:行者123 更新时间:2023-12-02 05:34:08 26 4
gpt4 key购买 nike

我开始学习 jigsaw java-9 功能并阅读了一些文章/视频。

我无法理解可选依赖项的概念( requires static )

引自article :

When a module needs to be compiled against types from another module but does not want to depend on it at run time, it can use a requires static clause. If foo requires static bar, the module system behaves different at compile and run time:

At compile time, bar must be present or there will be an error. During compilation bar is readable by foo.
At run time, bar might be absent and that will cause neither error nor warning. If it is present, it is readable by foo.

所以我想知道几件事:

  1. 为什么模块在编译时依赖于另一个模块,但在运行时不依赖?有什么例子吗?像 lombok 这样的乐器?

  2. java-9 之前的 java 中的可选依赖项有类似的吗?

附注

我又找到了一个解释:引用自article :

Sometimes we write code that references another module, but that users of our library will never want to use.

For instance, we might write a utility function that pretty-prints our internal state when another logging module is present. But, not every consumer of our library will want this functionality, and they don’t want to include an extra logging library.

In these cases, we want to use an optional dependency. By using the requires static directive, we create a compile-time-only dependency:

module my.module {
requires static module.name;
}

但对我来说绝对不清楚。有人能用简单的方式解释一下吗?

最佳答案

  1. 有相当多的库,只有在编译时使用它们才有意义。大多数情况下,这涉及仅在开发过程中提供帮助的注释(例如防止错误、减少样板文件)。一些示例包括:


    这些注释往往具有 SOURCECLASSRetentionPolicy,这意味着它们没有用(甚至没有用)可用)在运行时。为什么在部署时将这些依赖项与应用程序的其余部分一起提供?如果没有require static,您将被迫在部署时包含它们,否则您的应用程序将由于缺少依赖项而无法启动。

  2. 您也可以将这些依赖项声明为 Java 9 之前的可选依赖项。许多重要的 Java 项目都使用 Maven 或 Gradle 等构建工具。除了自动构建和测试项目的这些工具之外,它们所做的很大一部分工作是依赖管理。我对 Maven 不太熟悉,但是在使用 Gradle 时会使用:

    dependencies {
    compileOnly 'group.id:artifact-id:version'
    }

    声明运行时不需要的依赖项。

关于java - 为什么我们在java-9模块系统中需要require static?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56185582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com