Java 9 Platform Module system

Java 9 Platform Module System

Java 9 Platform Module System introduces the concept of modules that allow breaking up a project into logical parts. Modules provide better configuration and greater encapsulation. A module consists of classes and interfaces and a configuration file known as module-info.java. Module A can access only those members of Module B that have been exported by Module B. To specify that Module A needs Module B, we use the ‘requires’ keyword in the Module A configuration file. To specify all packages exported by a module we use the “exports” keyword in module-info.java file.
Lets look at an example of the module system using a ‘Hello World’ Example.

Example of Java 9 Platform Modules System

We write a class that prints Hello World followed by the name of a person.

Since printing Hello World followed by a name is a fairly complex operation 🙂 , we create a helper class that decorates the name to create the string ‘Hello World Mithil’

Note that the helper class is in a package called HelloWorldModuleHelper, whereas the HelloWorld class in a package called HelloWorldHelper. Normally, this would work fine. Here’s how we compile and run the class

In line 2 we compile the HelloWorldHelper class and put the class files in output/HelloWorldModuleHelper directory.
In line 4 we compile the HelloWorld class and put the HelloWorldHelper class in the classpath.
To run the HelloWorld class do this:

We run the HelloWorld class and put the Helper in classpath and all works well.
Its time now to introduce modules. We want to create two modules, one for the HelloWorld class and other for the HelloWorldHelper class.
Here’s how the module-info.java class for HelloWorldHelper looks like

To use this module in HelloWorldModule we will need to use the ‘requires keyword’

To specify which modules are included during compilation we specify the –module-path to javac and java

In line 3 we compile the module-info.java class, just like any other java class.
In line 6 we include the module path in javac using –module-path.
In line 10 we include the module path in java using –module-path. The result of running this program would be
‘Hello World Mithil’

This is how the directory structure now looks like

Modules_Directory_Structure
Modules_Directory_Structure

If you were to remove the ‘requires’ line from module-info.java, you would see this error:

The platform module system is a fundamental change to the Java language specification. In the next tutorial we will look at the JShell tool which is a very handy tool for rapid development and prototyping.

Java 9 Platform Module system

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top
Bitnami