Java SE Modularity
Java SE Platform and JDK are organized into 99 modules (as of Java SE 9.0.1) from single, monolithic versions of earlier releases. You can view the entire list by running the following command.
java --list-modules
.
java.base module
As the name denotes, java.base
is the base module for all the modules of JDK and each module implicitly depends on the base module.
Aggregator modules
In modularized java 9, there are aggregator modules acts as root modules. These modules conceptually group multiple modules. Java.se.ee
and java.se
are known for aggregator modules.
Incubator modules
Experimental API’s are part of incubator module. All incubator modules are prefixed with jdk.incubator. API’s that are shipped as part of incubator module is expected to change in future releases and be would be shipped as fully evolved modules.
As of Java 9, an experimental HTTPClient API is part of the modulejdk.incubator.httpclient
.
Creating modules in Java
Every module should describe how it is to be identified, What modules it depends on, and what API it exports.
module-info.java
Java application needs to be organized into modules and the first step to do that is to create a module. Module creation starts with a file module-info.java
denoted as module descriptor. A module descriptor is a .java file that describes the module being created. This file needs to be present at root source folder. A simple module descriptor looks as below.
module modulename_goes_here {
}
Here module is the new keyword introduced to create a module. modulename_goes_here is the placeholder where the actual module name is given. Module names must be unique within the application and suggested to follow the naming convention similar to that of packages.
A simple Sample module can be declared as follows.
module com.tbc.playarea {
}
Requires, requires transitive and exports
Once a module is created the next step is to specify explicitly the required modules that it depends on to function properly and packages it exports or made available to another module to access. By default, no package is made available to access outside the module unless explicitly exported from the module.
From the below illustration there are three modules Module 1, Module 2 and Module 2. that you exported from Module 1. Module 2 has a dependency on Module 1 and module 2’s descriptor indicates the same with keyword requires. And, same goes for Module 2 and Module 2. Another important aspect to note is that module 2 specifies transitive requires on module 1. Hence whichever module depends on module 2 will automatically have access to Module 1 exported packages. In this case, Module 3 gets access to module 1’s com.module1.package1.
Fig : requires, exports and requires transitive illustration.