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?
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:
- it compiles
.java
files (we havemodule-info.java
defineopens com.foo.abc;
andcom/foo/abc
directory ("package") does not exist) - it creates
com/foo/abc
directory - it copies there
config_dev.properties
file, at this step decision made for what environment we make build (PROD/TEST/DEV) - 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