Java 9 中 module-info 文件中的"export"子句有什么用?

javaobject oriented programmingprogramming更新于 2025/10/31 15:40:17

模块是代码和数据的组合,它具有名称,声明对其他模块的依赖,导出包含可在此模块外部访问的公共类型的包,并指定它使用的服务或它提供的服务实现。所有这些都已在 module-info.java 文件中指定,该文件包含在模块的根目录中。

在"module-info.java"中可以使用两种类型的"export"子句文件。

1) export <package>:默认情况下,模块的 public  类型在模块外部不再可见。要使给定包的公共类型在其他模块中可见,我们必须 export  此包。我们必须记住,我们处于包级别,而不是类型的单元级别。但是,子包不会被导出。

我们需要允许其他模块使用包 tp.com.tutorialspoint.model 的类和接口,我们可以这样写:

module com.tutorialspoint.model {
   exports tp.com.tutorialspoint.model;

了解一个包只能存在于一个模块中非常重要。否则,我们将收到以下错误:

Error:(1, 1) java: package exists in another module:

2) 将 <package> 导出到 <module>:我们可以通过将某些包的可见性降低到有限的模块列表来增强模块的安全性:只有列出的模块才能访问这些类。

module com.tutorialspoint.model {
   exports tp.com.tutorialspoint.model
      to com.tutorialspoint.gui;
}

相关文章


有用资源