模块声明中的 requires 和 requires static 有什么区别

What's the difference between requires and requires static in module declaration

requiresrequires static[=有什么区别20=] 模块声明中的模块语句?

例如:

module bar {
    requires java.compiler;
    requires static java.base;
}

两者的主要区别在于

requires static foo.module;

依赖在静态阶段、编译期间是强制的,但在动态阶段是可选的,在另一方面

requires bar.module;
添加

以声明该模块按名称依赖于其他一些模块,在编译时和 运行 时。

A requires 子句表示在编译和 运行 时需要所需的模块。因此,当模块系统在 module resolution 期间(处理模块描述符和解决依赖关系的阶段)遇到这样的子句时,它会搜索可观察模块的范围(JDK 中的模块和模块路径)并在找不到模块时抛出错误。

一个requires static子句表示a dependency that is optional at run time。这意味着在编译时模块系统的行为与上述完全相同。

另一方面,在 运行 时,它主要忽略 requires static 子句。如果它遇到一个,它 不会解决它 。这意味着,如果一个可观察模块仅被 requires static 引用,它不会进入模块图中!起初这可能有点令人惊讶。另一方面,如果该模块以其他方式进入图表(其他模块需要,added manually with --add-modules, drawn in by service binding), all modules that have an optional dependency on it can read 它。