为什么从Java模块中打开不存在的包? [英] Why open a non-existing package from a Java module?

查看:102
本文介绍了为什么从Java模块中打开不存在的包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JLS 11 "7.7.2.导出和打开的包" 说:

允许opens指定一个与当前模块关联的编译单元未声明的包.

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?

推荐答案

感谢 Alan Bateman Michael Easter 的解释,我可以想到一些现实的情况.

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

首先,正如艾伦(Alan)和迈克尔(Michael)所解释的那样:JLS允许在没有Java类型的情况下打开"目录,以便在我们将资源保留在其中的情况下使用.因此,对我们来说,这些是资源目录",但JLS将其命名为package which is not declared by a compilation unit.它甚至不是允许"的问题,而是必须"的问题.如果没有用于资源目录(com/foo/abc)的opens指令,则另一个模块无法读取这样的资源:

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");

第二,我写这个问题主要是因为我不知道opens允许指定甚至不存在的包"(目录),尽管它给出警告,但编译成功. 我可以想到一个可能的情况,用于模块化JAR文件的构建脚本:

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. 它会编译.java个文件(我们已经module-info.java定义了opens com.foo.abc;,而com/foo/abc目录(包")不存在)
  2. 它创建com/foo/abc目录
  3. 它会复制config_dev.properties个文件,在此步骤中,我们决定要建立哪种环境(PROD/TEST/DEV)
  4. JAR文件已打包,包含字节码和资源.
  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.

如果不允许不存在目录的opens,则第1步将失败.但这只会在编译时发出警告,这是可以的.

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.

这篇关于为什么从Java模块中打开不存在的包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆