The module system introduced in Java 9 makes it easier to organize your code. Here’s a brief guide to working with modules in Java
Until Java 9, Java’s top-level code organization element had been the package. Starting with Java 9 that changed: above the package now is the module. The module collects related packages together.
The Java Platform Module System (JPMS) is a code-level structure, so it doesn’t change the fact that we package Java into JAR files. Ultimately, everything is still bundled together in JAR files. The module system adds a new, higher-level descriptor that JARs can use, by incorporating the module-info.java file.
Large-scale apps and organizations will take advantage of modules to better organize code. But everyone will be consuming modules, as the JDK and its classes are now modularized.
Why Java needs modules
JPMS is the outcome of project Jigsaw, which was undertaken with the following stated aims:
- Make it easier for developers to organize large apps and libraries
- Improve the structure and security of the platform and JDK itself
- Improve app performance
- Better handle decomposition of the platform for smaller devices
It’s worth noting that the JPMS is a SE (Standard Edition) feature, and therefore affects every aspect of Java from the ground up. Having said that, the change is designed to allow most code to function without modification when moving from Java 8 to Java 9. There are some exceptions to this, and we’ll note them later in this overview.
The chief idea behind a module is to allow the collection of related packages that are visible to the module, while hiding elements from external consumers of the module. In other words, a module allows for another level of encapsulation.
In practical terms, modules help manage dependencies more efficiently. For instance, in a large codebase, you can define which parts of your code are exposed to other modules and which parts are internal. This is done through the module-info.java file, where you specify the module’s name, its dependencies, and the packages it exports.
Another significant advantage of the module system is that it can help with reducing the size of applications. By knowing exactly which parts of the code are necessary, the Java runtime can strip away unnecessary parts, which is particularly useful for smaller devices and cloud deployments.
Overall, the introduction of JPMS has added a powerful tool for developers, helping to create more maintainable, secure, and performant Java applications.