What is the use of the "requires" clause in a module-info file in Java 9?

JavaObject Oriented ProgrammingProgramming

A module is an important concept introduced in Java 9. By using this concept, we can able to divide code into smaller components called modules. Therefore, each module has its own responsibility and declare its dependency on other modules to work properly. In order to declare a module, we need to include the "module-info.java" file to root source code.

There are few types of "requires" clause in "module-info" file

1)  requires <module>: By default, a module doesn't know other modules present in a module-path. So, it is necessary to add a line in our module-info.java: "requires" each time when we want to access another module.

module com.tutorialspoint.gui {
   requires com.tutorialspoint.model;
   requires java.desktop;
}

2) requires transitive <module>: In the case of our module "com.tutorialspoint.model": returns exported interface types of module "com.core". Therefore, any module that wants to use then it also requires "com.core" to access the classes of this second module with compilation errors. Java 9 allows the keyword "transitive" to indicate that by transitivity. Users "com.tutorialspoint.model" can be able to access "com. core" that allows implementation changes easily.

module com.tutorialspoint.model {
   requires transitive com.core;
}

3) requires static <module>: The keyword "requires static" represents the concept of optional dependence such a module is:

  • mandatory at compilation: a compilation error can be raised if the module is not present in the path module at compilation.
  • optional at runtime: the module can't be taken into account in the sanity check phase when an application is started. The application starts even if the module is not present.

For instance, we want to propose the persistence of the data of an application, either in an oracle database or h2database.

module com.tutorialspoint.model {
   requires static ojdbc
   requires static h2daabase.h2; 
}


raja
Published on 27-Apr-2020 13:20:14
Advertisements