Java Module Declaration笔记
kinds of modules
- normal modules
- A normal module, without the open modifier, grants access at compile time and run time to types in only those packages which are explicitly exported.
- open modules
- An open module, with the open modifier, grants access at compile time to types in only those packages which are explicitly exported, but grants access at run time to types in all its packages, as if all packages had been exported.
Dependences
- requires
指定需要依赖的模块名称
java.base 无法使用此指令(java.base为起始模块)
所以其他模块儿默认隐性依赖此模块
可选修饰符- transitive 依赖传递
- static 编译时强制, 运行时可选
重复依赖同一模块,将导致编译时错误:Duplicate requires entry:
Exported and Opened Packages
- exports
- The exports directive specifies the name of a package to be exported by the current module. For code in other modules, this grants access at compile time and run time to the public and protected types in the package, and the public and protected members of those types (§6.6). It also grants reflective access to those types and members for code in other modules.
- opens
- The opens directive specifies the name of a package to be opened by the current module. For code in other modules, this grants access at run time, but not compile time, to the public and protected types in the package, and the public and protected members of those types. It also grants reflective access to all types in the package, and all their members, for code in other modules.
exports 不能导出与当前模块无关的package,opens 可以
exports 多次相同包,将导致编译时错误
opens 多次相同包,将导致编译时错误
opens 不能出现在open模块中
to 子句 不可重复指定同一个包
to 字符可以指定限定模块不可见,也可以指定限定模块可见
Service Consumption
- uses
- The uses directive specifies a service for which the current module may discover providers via java.util.ServiceLoader.
uses 可以是class、interface、annotation,不可以为enum,否则将导致编译时错误
service可以在当前模块,也可以不在当前模块,但必须可以被当前模块访问,否则将发生编译器异常
users 同一服务仅能指定一次
Service Provision
- The provides directive specifies a service for which the with clause specifies one or more service providers to java.util.ServiceLoader.
provides 可以是class、interface、annotation,不可以为enum,否则将导致编译时错误
service可以在当前模块,也可以不在当前模块,但必须可以被当前模块访问,否则将发生编译器异常
每个提供者 class、interface必须是公共的,且必须是顶级类或者是嵌套静态类,否则将发生编译时异常
每个服务提供者必须被声明在当前模块
While a service provider that is specified by a provides directive must be declared in the current module, its provider method may have a return type that is declared in another module. Also, note that when a service provider declares a provider method, the service provider itself need not be a subtype of the service.
Unnamed Modules
- An observable ordinary compilation unit that the host system does not associate with a named module (§7.3) is associated with an unnamed module.
未命名模块间相互可见
未命名模块对于命名模块不可见,因为无法使用requires,但是可以使用运行时反射API进行调用访问
Observability of a Module
- A module is observable if at least one of the following is true:
- A modular compilation unit containing the declaration of the module is observable.
- An ordinary compilation unit associated with the module is observable.