Getting Started with Java 9 Module System
The Java platform module system (JSR 376) a.k.a Project Jigsaw is on target to be part of the JDK 9 release. The goals of the system as described by the JSR are:
- Reliable configuration, to replace the brittle, error-prone class-path mechanism with a means for program components to declare explicit dependencies upon one another, along with
- Strong encapsulation, to allow a component to declare which of its public types are accessible to other components, and which are not.
IntelliJ IDEA already has a concept of modules for a project. Every IntelliJ IDEA module builds its own classpath.
With the introduction of the new Java platform module system, IntelliJ IDEA modules had to extend their capability by supporting the Java platform's module-path if it is used instead of the classpath.
In this tutorial we explore where IntelliJ IDEA assists in creating and using Java Platform modules and how these modules work with IntelliJ IDEA modules.
We will use the 'Greetings World' example given in full in the OpenJDK quick start guide.
Creating a module
After creating a module in IntelliJ IDEA we can define it as a Java Platform module by creating a module-info.java file under the module source directory.
Every IntelliJ IDEA module can have at most a single Java platform module.
We can create a new module-info.java for our module by selecting the source directory where we want to create it and using the menu option New | module-info.java
When creating the module-info.java declaration file, IntelliJ IDEA will choose the name of the IntelliJ IDEA module as the default name for the Java Platform module. This can be changed and is not required to match.
Using a module
The dependencies of a module need to be defined in IntelliJ IDEA and Java Platform (Jigsaw) modules.
IntelliJ IDEA helps us keeping them in sync.
To define dependencies between our project modules, We can write a
requires declaration in module-info.java and then IntelliJ IDEA will suggest to us to also add it as a dependency in its module.
This works also with library dependencies but only if the library jar file was already declared as a project dependency.
From the other direction, we can just write our java code. IntelliJ IDEA will suggest to add the other module as a dependency on our current module and then will also suggest to us adding a
requires declaration as well.
Running with modules
The information declared in the Java platform modules is used when running a class Ctrl+Shift+F10 in IntelliJ IDEA.
This means that IntelliJ IDEA will run the JVM using a module-path and not a classpath.
This will enforce the strong encapsulation we get from the module system and any dependency issues we might have will be then reproduced by this run.