Why do we need requires static in java-9 module system? [duplicate]

折月煮酒 提交于 2019-12-01 07:47:53
  1. There are a decent number of libraries out there where it only makes sense to have them at compile time. Mostly this deals with annotations that only exist to help during development (e.g. prevent bugs, reduce boilerplate). Some examples include:


    These annotations tend to have a RetentionPolicy of SOURCE or CLASS, which means they aren't useful (or even available) at runtime. Why ship these dependencies with the rest of your application when you deploy? Without requires static you would be forced to include them when you deploy, otherwise your application would fail to start due to missing dependencies.

  2. You would declare these dependencies as optional pre-Java 9 as well. Many Java projects of any significance use a build tool such as Maven or Gradle. In addition to those tools automatically building and testing your project, a large part of what they do is dependency management. I'm not familiar enough with Maven, but when using Gradle one would use:

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

    To declare dependencies that are not needed at runtime.

If Dependent Module should be available at compile time but optional at rumtime, then such type of Dependency is called Optional Dependency. We can Specify optional dependency by using static keyword.

Note The static keyword is used to say that "This dependency check is mandatory at compile time and optional at runtime."

Eg.1

module moduleB {
  requires moduleA;
}

moudleA should be available at the time of compilation & rumtime. it is not Optional Dependency.

Eg2.

module moduleB {
   requires static moduleA;
}

At the time of compilation moduleA should be available, but at runtime it is optional ie, at runtime even moduleA is not avaiable JVM will execute code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!