为什么不允许导出整个模块? [英] Why is exporting the entire module not allowed?

查看:159
本文介绍了为什么不允许导出整个模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 9的模块声明中有2个构造:

  exports com.foo; 

 打开com.foo; 

其中 exports 授予编译时访问权限,而打开允许运行时访问,作为反射和资源。



打开 exports 有一个宽容,您可以将整个模块定义为打开,结果与显式打开每个包相同:

  open module com.mod {

但是没有类似的构造

 导出模块com.mod {

我的问题:为什么会这样;是什么决定允许一次打开整个模块而不是导出?

解决方案

模块的导出定义了它的API,应该刻意设计并保持稳定。 导出的模块可能通过添加,删除或重命名包而轻易地且无意中更改其API,这将违背稳定性目标。 (这与没有通配符导出的原因基本相同,例如 exports foo.bar。* )。



<另一方面,打开包并不真正定义模块的API。当然,代码可以依赖于只能通过反射访问的功能,但是当用于访问内部时,Java社区通常将反射视为黑客。



它更广泛(并且更有益)用于访问工件以为其提供服务(XML / JSON序列化,持久性,依赖性注入......)。在这种情况下,反映在模块上的代码不会依赖,因此不会被移动的东西打破。因此没有理由保持打开的软件包稳定,这使得像开放模块这样的免费方法成为可能。


In Java 9's module declaration there are 2 constructs:

exports com.foo;

And

opens com.foo;

Where exports grants compile-time access, while opens allows runtime access, as reflection and resources.

opens has one leniency over exports that you can define the whole module as open, resulting the same as explicitly opening every package:

open module com.mod {

But there's no similar construct

exported module com.mod {

My Question: Why is it so; what decisions has been made to allow opening the whole module at once but not with exporting?

解决方案

A module's exports define its API, which should be deliberately designed and kept stable. An "exported module" could easily and inadvertently change its API by adding, removing, or renaming packages, which would go against the stability goal. (This is essentially the same reason why there are no "wildcard exports" like exports foo.bar.*).

Open packages, on the other hand, do not really define a module's API. Sure, code can depend on functionality that is only accessible via reflection, but the Java community generally sees reflection as a "hack" when used to access internals.

Its much wider (and more beneficial) use is to access an artifact to provide a service for it (XML/JSON serialization, persistence, dependency injection, ...). In such cases, the code reflecting over the module does not depend on it and is hence not broken by moving stuff around. There is hence less reason to keep the opened packages stable, which makes a free-for-all approach like open modules feasible.

这篇关于为什么不允许导出整个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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