Java 9 Modularity
Have you ever experienced
NoClassDefFoundErrorat runtime (Its because of missing dependencies) and spent hours and days trying to track down irreproducible bugs in your production environment, just to find out that somehow two versions of 3rd party dependencies have managed to sneak into your classpath. Tracking them down is a painful experience eventhough we use sophisticated IDEs.
Its time to get rid of those nasty surprises and replace the classpath with the module path.
What is a module?
A module is the collection of code. It is a holder for classes, data and other modules in the form of dependencies. It is similar to JAR files but better. But there is one crucial difference: one of the files is called module-info.java. As the name suggests, it declares our module. It defines
- the unique name of our module
- which other modules our module depends on
- which packages are to be exported to be used by other modules
It is a new and better way to share code with programmers and collaborate without issues.
How Modules work?
A module contains a module-info.java file which contains all the settings for the module and the dependency modules.
Two main keywords to use modules are
requiresand
exports
1 2 3 4 |
module Decoder{ requires Reader; exports com.harinathk.decoder; } |
1 2 3 |
module Reader{ exports com.harinathk.reader; } |
Below are the classes for Reader and Decoder module respectively. The Decoder module requires the Reader module to retrieve the data to be decoded through the use of a scanner.
1 2 3 4 5 6 |
package com.harinathk.reader; public class Scanner{ public static String name() { return "scanner from Reader package"; } } |
1 2 3 4 5 6 7 |
package com.harinathk.decoder; import com.harinathk.reader.Scanner; public class Main { public static void main(String[] args) { System.out.format("Reading with a %s!%n", Scanner.name()); } } |
Conclusion
Modules enables to structure our code in a more modular way by providing strong encapsulation and reliable configuration, but still allows loose coupling of modules.
Modules also allows you to get away from class path issues such as those obscure bugs which turn out to be an old version of the jar already on your class path. Java finally gets the level of dependency control we now take for granted in Maven and other tools. It is time to say good bye to class path hell.