Project Jigsaw, The Java Platform Module System (JPMS), Modularity, JSR 277, JSR 376... These are the names of one of the most significant features of Java 9. Modularity reduces the complexity of the system by providing:
- Explicit dependencies
- Clear interface
- Strong encapsulation
Modularity is also arguably one of the terrifying Java features of all times. Despite these numerous benefits, proper modules are still rare species in the Java world.
The purpose of this cheat sheet is to show that modules in Java are friendly to us, developers, and easy to use. The Module Declaration (module-info.java) section explains how to define modules. The Module Path vs Class-Path section will be helpful for people migrating existing non-modular applications to JPMS.
Module Declaration (module-info.java)
- Module Name and Minimal Module Declaration
- Dependencies
- API
- Other Stuff: Services, Annotations, and Formal grammar of the module declaration file
Here are some of important questions about support of old-style non-modular jar in Java 9+. It's better than what you think! π
...and...
YES! and YES! But... if...:ballot_box_with_check:it's Java 9 friendly, e.g., it doesn't use private API or split packages.
Read more:
π Java 9 Migration Guide: The Seven Most Common Challenges: https://blog.codefx.org/java/java-9-migration-guide/
In JPMS, you can convert existing non-modular jars into:
- Unnamed modules, when passed on classpath;
- Or, automatic modules, when passed on module path.
See Module Path vs Class Path.
A module declaration is a file which defines the dependency graph:
- Dependencies: Which other modules this module depends on;
- API: which parts of this module other modules can use: at compile time or at runtime.
To create a module declaration:
βοΈ Create a file named module-info.java
βοΈ By convention, it should be placed at the root source folder, e.g., next to the com
or org
folders.
A minimal module declaration defines its name:
module com.mycompany.myproject {
}
π£π₯ The module name must be globally unique - the name conflicts are prohibited. A recommended practice is to use a reverse-domain-name pattern |
Dependencies are other modules this module needs for its work - it requires these modules.
module com.mycompany.myproject { // the module name should be unique
// dependency on `com.example.foo.bar` which must be present both at compile time AND runtime
requires com.example.foo.bar;
// transitive dependency: any module which requires current module will also *implicitly* depend on this dependency
requires transitive com.kitties.bar;
// optional dependency is mandatory at compile time, but optional at runtime
requires static com.owls.foo;
}
Read more:
π Optional Dependencies: https://blog.codefx.org/java/module-system-optional-dependencies/
π Transitive Dependencies: https://blog.codefx.org/java/implied-readability/
In pre-Java 9 world any public class was available everywhere and could be used by any other class. The "internal" packages were not in fact internal. With Java 9, module's contents are not available to the external classes by default; one must explicitly define what the module exposes to outside world so that other modules could use it either in compile time or via reflection. Module's API is now expressly specified in the module's declaration.
|
All Code |
|
All Code | ||
Modules from the "to" clause | Modules from the "to" clause | ||||
NO access | All Code |
|
All Code | ||
Modules from the "to" clause | Modules from the "to" clause |
A package can be exported or opened in
- π Module declaration (
module-info.java
file). It's a recommended approach when you have control over this file. - π Or, as a command line option, if you have no other choice.
exports packageName |
n/a | ||
exports packageName to targetModule
|
--add-exports sourceModule/packageName=targetModule(,targetModule)* The target-module can be ALL-UNNAMED to export to all unnamed modules |
||
opens packageName |
n/a | ||
opens packageName to targetModule |
--add-opens sourceModule/packageName=targetModule(,targetModule)* |
Read more:
π Java Platform, Standard Edition Tools Reference > Main Tools to Create and Build Applications > java: https://docs.oracle.com/javase/9/tools/java.htm#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE__GUID-AC22D7B8-E3C4-4554-AE49-A62C9421AA7C
π Five Command Line Options To Hack The Java 9 Module System: https://blog.codefx.org/java/five-command-line-options-to-hack-the-java-9-module-system/
The exports
directive defines what this module exposes to other modules at runtime and compile time.
module com.mycompany.myproject { // the module name should be unique
// unqualified export => grants access to ALL other modules
exports com.mycompany.myproject.foo;
exports com.mycompany.myproject.foo.internal
// having a "to" clause means that this is a **qualified export** => exports the package only to the friends of the current module - the modules specified in the `to` clause
to com.example.x;
exports com.mycompany.myproject.bar.internal to com.example.y, com.example.z;
}
The opens
directive opens the module to the outside modules for the reflection. It's usually useful when using reflection-based frameworks such as Spring or Guice;
βοΈ As for the code from inside of the current module, it can still reflectively access all types and members from the module regardless whether they were opened or not |
module com.mycompany.myproject { // the module name should be unique
// `opens` the package for reflection to ALL other modules
// * compile time: no access at all
// * runtime: to all types, including private types, and all their members, including private ones
opens com.mycompany.myproject.ollie;
// a qualified `opens` directive - only modules from the `to` cause can access this package at runtime
opens com.mycompany.myproject.ollie.internal to org.anothercompany.coolframework;
// Also see a section about the open modules - a module which opens ALL its packages
}
An open module opens
all its packages. To define it, add the open
modifier before the module
:
open module com.mycompany.myproject {
}
Services implemented with use of ServiceLoader
existed in Java well before Java 9. Their goal is to do decouple the interface and its implementation(s). Now, in Java 9, we can declare services and their usages in the module-info.java
:
Service consumer:
module com.mycompany.serviceconsumer {
// Use an existing service. The implementation can be accessed in code by using the ServiceLoader
uses com.example.foo.ServiceInterface;
}
Service provider:
module com.mycompany.service {
// Register a new service implementation for com.example.foo.ServiceInterface
provides com.example.foo.ServiceInterface
with com.example.foo.ServiceImpl;
}
βοΈ Service consumer and service provider can also be defined in the same module. |
Module declarations can also have annotations, e.g., the @Deprecated
annotations:
/**
* This module was replaced by a new module performing the same job much better!
* @deprecated use {@link com.mycompany.newcoolmodule} instead.
*/
@Deprecated
module com.mycompany.oldmodule {}
OK, open modules, annotations... What else? β A structure of a module declaration may seem too complicated. But it's not! Just see the grammar for module files (taken from section 7.7 of Java 9 Language Specification):
ModuleDeclaration:
{Annotation} [open] module Identifier{.Identifier}
{ {ModuleDirective} }
ModuleDirective:
requires {RequiresModifier} ModuleName ;
exports PackageName [to ModuleName {, ModuleName}] ;
opens PackageName [to ModuleName {, ModuleName}] ;
uses TypeName ;
provides TypeName with TypeName {, TypeName} ;
RequiresModifier:
(one of)
transitive static
ModuleName:
Identifier{.Identifier}
|
Explicitly defined module | Automatic module | |
|
Unnamed module | Unnamed module |
You can mix module path and classpath!
Read more:
π Java Platform, Standard Edition Tools Reference > Main Tools to Create and Build Applications > java: https://docs.oracle.com/javase/9/tools/java.htm#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE__BABDJJFI
As you can see from the table above:
- Everything on the module path, regardless whether it's a plain jar or a jar with a module-info, becomes a named module.
- Similarly, everything on the classpath, regardless whether it's a plain jar or a jar with a module-info, becomes an unnamed module.
In fact, there are three module types:
- Named:
- Explicit
- Automatic
- Unnamed
Explicit modules follow the rules for Dependencies and API defined in its Module Declaration (module-info.java)
Automatic modules are plain JARs (no module descriptor) on the module path.
βοΈ reads vs requires "Module1 reads Module2" means that Module1 can access types from Module2's exported packages. A module that requires another module also reads the other module. |
As they don't have a module-info.class
, this information will be calculated using the following rules:
- Name:
Automatic-Module-Name
fromMANIFEST.MF
if it's present. Derived from the JAR name otherwise.- They can be referenced using this name;
- See http://branchandbound.net/blog/java/2017/12/automatic-module-name/ for details;
- For Eclipse plug-ins, see https://dev.eclipse.org/mhonarc/lists/cross-project-issues-dev/msg14888.html;
- Dependencies:
- It
requires transitive
all other resolved modules; - Reads the
unnamed
module;
- It
- API:
- Exports all its packages;
- The module can be referenced in other modules'
module-info.java
using its calculated name.
Everything on the classpath becomes an unnamed module.
Name: No name;- Dependencies:
- Reads all other modules
- Can read or open other
ALL-UNNAMED
in the command line
- API:
- Because it does not have a name, it cannot be referenced in module-info.java.
- Readable only by automatic modules
π Java Language Specification. Chapter 7. Packages and Modules. https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html
ππ² The Java Module System by Nicolai Parlog : https://www.manning.com/books/the-java-module-system
Disclaimer: I was a manuscript reviewer of this book and, thus, got a free copy of it from Manning.
ππ² Java 9 Modularity by Sander Mak, Paul Bakker: https://javamodularity.com/
π Understanding Java 9 Modules: https://www.oracle.com/corporate/features/understanding-java-9-modules.html
π Programming with Modularity and Project Jigsaw. A Tutorial Using the Latest Early Access Build https://www.infoq.com/articles/Latest-Project-Jigsaw-Usage-Tutorial
π Sander Mak on the Java Module System: https://www.infoq.com/podcasts/Sander-Mak-module-system-Java9
π₯ Designing for Modularity with Java 9: https://www.youtube.com/watch?v=tamVhtV18dY
- ajaxorg/ace#3628
- The Java Module System by Nicolai Parlog : https://www.manning.com/books/the-java-module-system