Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 552
Barat Sahdzijeu Avatar asked Oct 16 '22 15:10

Barat Sahdzijeu


1 Answers

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.

like image 70
Barat Sahdzijeu Avatar answered Oct 18 '22 22:10

Barat Sahdzijeu