Why open a non-existing package from a Java module?

橙三吉。 提交于 2019-12-07 05:12:35

问题


The JLS 11 "7.7.2. Exported and Opened Packages" says:

It is permitted for opens to specify a package which is not declared by a compilation unit associated with the current module.

What would be a scenario for this? Why is this needed?


回答1:


Thanks to Alan Bateman and Michael Easter for explanations, and I can think of some realistic scenarios.

First, as was explained by Alan and Michael: JLS allows to "open" directories without Java types for situations when we keep resources in them. So, for us these are "resource directories", but JLS names it as package which is not declared by a compilation unit. And it's not even question of "allows" but rather "must". Without opens directive for resources directory (com/foo/abc), another module cannot read resource like that:

InputStream is = ClassLoader.getSystemResourceAsStream("com/foo/abc/config.properties");

Second, I wrote this question mostly because I was puzzled that opens allows to specify even non-existing "packages" (directories), although it gives warnings, but compiles successfully. A possible scenario behind that I can think of a build script for modular JAR file:

  1. it compiles .java files (we have module-info.java define opens com.foo.abc; and com/foo/abc directory ("package") does not exist)
  2. it creates com/foo/abc directory
  3. it copies there config_dev.properties file, at this step decision made for what environment we make build (PROD/TEST/DEV)
  4. JAR file is packaged, containing bytecode and resources.

In case opens for non-existing directory was not allowed, step #1 would fail. But it only gives a warning during compile time, which is Ok.



来源:https://stackoverflow.com/questions/56147221/why-open-a-non-existing-package-from-a-java-module

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