What are the components in a module-info file in Java 9?

JavaObject Oriented ProgrammingProgramming

A module is an independent unit of application that represents a single functionality. A module contains three important components

  • Name: To uniquely identify it
  • Dependencies: Other modules in which it depends on
  • Exported packages: Packages which are open for external application

In order to declare a module, we need to add the "module-info.java" file to the root source code. The components of the "module-info.java" file includes "name", "requires", "exports", and "exports to".

Below is the template of "module-info.java" file

module <module-name> {
   requires <module-name1> ;
   requires <module-name2>;
   ...
   exports <package-name1>;
   exports <package-name2>;
   ...
   exports <package-name> to <module-name>;
}
  • Name: It is an important characteristic of a module. The modular system identifies a module by name, so it is unique.
  • requires: This clause can be used to define dependencies and external module in which the current module depends on. We need to have separate "requires" entry for each dependent module in "module-info.java". Java 9 has a base module. It is an independent module that doesn’t require any other module. We don’t have to specify using the "requires" clause in a module. This base module is available by default.
  • exports: The "exports" clause is to define packages of current module exports. These packages are open for other modules to use. We need to have separate "exports" entry for each exported module in "module-info.java" file
  • exports to: The "exports to" clause are to export a package only to specific modules rather than exporting it for everyone.
raja
Published on 20-Mar-2020 07:07:25
Advertisements