Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 18 - Modern Java Features 8 to 21

Java 9 Module System Jigsaw with module-infojava Explained

Reviewed & accurate
AI Summary

Introduction

The Java Platform Module System, known as Project Jigsaw, shipped with Java 9 in September 2017 after more than eight years of design work via JSR 376 and JEPs 200 through 261. Its goal was to make the JDK itself modular so that a runtime image could contain only the modules an application needs, and to give application developers a way to express strong encapsulation at the package level. The output is the module-info.java file: a single declaration at the root of a module that states which packages it exports, which modules it requires, and which services it provides or consumes.

For a Java learner, java 9 modules jigsaw is the moment Java caught up with OSGi and Java EE's earlier bnd tools, but with first-class compiler and runtime support. This post shows what a module-info.java file looks like, how requires and exports shape the dependency graph, how opens supports reflective access from frameworks like Hibernate and Spring, and how to compile and run a small two-module program with javac and java.

What is the Java 9 Modules Jigsaw System?

The Jigsaw module system belongs to the family of module systems for the JVM, alongside OSGi (Apache Felix, Eclipse Equinox), JBose Modules, and the Kotlin Gradle module metadata. A module is a named, versioned collection of packages with an explicit list of dependencies. Unlike the classpath, which lets every class see every other class, the module path enforces readability: a module can only access the exported packages of modules it explicitly requires, and reflective access to non-exported packages is denied unless opens is used.

The unit of declaration is the file module-info.java at the root of the module source tree. Its syntax is a small DSL: module name, then zero or more requires, exports, opens, uses, and provides directives. The compiled module-info.java becomes module-info.class, which the JVM loads at startup to build the module graph that controls visibility.

How the Jigsaw Module System Works - Step by Step

Step 1: Define the module. Create a directory mylib/src/com/example/ with the source files, and at mylib/src/module-info.java declare "module com.example.lib { exports com.example.lib.api; requires java.sql; }". The exports directive makes the api package visible to other modules; the requires directive declares that this module depends on the standard java.sql module.

Step 2: Compile the module. Use "javac -d mylib/out --module-source-path mylib/src $(find mylib/src -name '*.java')" so that the module-info.class and the package classes land in mylib/out/com.example.lib/. The output directory tree is now a compiled module.

Step 3: Define the consuming module. Create myapp/src/module-info.java declaring "module com.example.app { requires com.example.lib; }". The requires directive makes the public API of the lib module visible inside the app module.

Step 4: Compile the consuming module with the module path. Use "javac -p mylib/out -d myapp/out --module-source-path myapp/src $(find myapp/src -name '*.java')". The -p flag (short for --module-path) tells the compiler where to find required modules.

Step 5: Run the application. Use "java -p mylib/out:myapp/out -m com.example.app/com.example.app.Main". The -m flag (short for --module) names the main class to launch. The JVM resolves the module graph and refuses to start if any required module is missing or if the code attempts to access a non-exported package.

Java Program for Jigsaw Modules

// =============================================================
// FILE: com.example.lib/src/module-info.java
// =============================================================
module com.example.lib {
    requires java.sql;
    exports com.example.lib.api;
    // com.example.lib.internal is intentionally NOT exported
}

// =============================================================
// FILE: com.example.lib/src/com/example/lib/api/Greeting.java
// =============================================================
package com.example.lib.api;

import com.example.lib.internal.Formatter;

public class Greeting {
    private final String name;
    public Greeting(String name) { this.name = name; }
    public String render() {
        return Formatter.format("Hello, " + name + "!");
    }
}

// =============================================================
// FILE: com.example.lib/src/com/example/lib/internal/Formatter.java
// =============================================================
package com.example.lib.internal;

// NOT exported - other modules cannot reference Formatter directly.
public class Formatter {
    public static String format(String input) {
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\s+");
        return p.matcher(input.trim()).replaceAll(" ");
    }
}

// =============================================================
// FILE: com.example.app/src/module-info.java
// =============================================================
module com.example.app {
    requires com.example.lib;
}

// =============================================================
// FILE: com.example.app/src/com/example/app/Main.java
// =============================================================
package com.example.app;

import com.example.lib.api.Greeting;
// import com.example.lib.internal.Formatter; // COMPILE ERROR

public class Main {
    public static void main(String[] args) {
        Greeting g1 = new Greeting("   imcseian    reader  ");
        System.out.println(g1.render());

        // Attempting reflection on the internal package will fail
        // at runtime unless the lib module uses "opens" on it.
        try {
            Class<?> f = Class.forName("com.example.lib.internal.Formatter");
            Object result = f.getMethod("format", String.class)
                             .invoke(null, "reflected");
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("reflection blocked: " + e.getClass().getSimpleName());
        }
    }
}

Code Explanation - Line by Line

The lib module's module-info.java declares three facts: it requires java.sql because Formatter or other classes inside it might use JDBC types in a real version; it exports com.example.lib.api so other modules can call Greeting; and it deliberately leaves com.example.lib.internal unexported, which means the Formatter class is part of the implementation and should not be used by external code. The compiler enforces this: an attempt to write "import com.example.lib.internal.Formatter" in a consuming module fails at compile time with "package com.example.lib.internal is declared in module com.example.lib, which does not export it".

The api package contains Greeting, a small public class that delegates to Formatter to collapse repeated whitespace. The internal package contains Formatter, which uses java.util.regex.Pattern to do the actual work. The implementation detail is hidden behind the public api package, which is exactly what strong encapsulation is meant to provide.

The app module's module-info.java declares only one directive: requires com.example.lib. That single line is what makes Greeting visible. The app module does not require java.sql even though lib does, because requires is not transitive by default; only the explicit requires transitive keyword would propagate a dependency to downstream consumers.

The Main class imports Greeting from the api package and creates two instances, then prints the rendered string. The uncommented import of Formatter shows what would fail to compile if uncommented. The reflection block uses Class.forName and getMethod to try to invoke Formatter.format from outside the module; without an "opens com.example.lib.internal" directive in the lib module-info.java, the JVM throws an InaccessibleObjectException at runtime, demonstrating that the module system's enforcement runs both at compile time and at runtime.

Sample Input and Output

$ javac -d com.example.lib/out --module-source-path com.example.lib/src \
    $(find com.example.lib/src -name '*.java')
$ javac -p com.example.lib/out -d com.example.app/out \
    --module-source-path com.example.app/src \
    $(find com.example.app/src -name '*.java')
$ java -p com.example.lib/out:com.example.app/out \
    -m com.example.app/com.example.app.Main
Hello, imcseian reader!
reflection blocked: InaccessibleObjectException

The first line of program output shows the public api path worked: Greeting called Formatter internally and produced a normalised string. The second line shows that reflective access to the internal package was blocked by the module system, which is the whole point of strong encapsulation. If you added "opens com.example.lib.internal" to the lib module-info.java, the second line would instead print "reflected".

Common Mistakes to Avoid

The first mistake is omitting the module-info.java file at the right path. The file must live at the root of the module source directory, not inside any package. Placing it under com/example/ will cause the compiler to fail with "module declaration ... should be in a file named module-info.java". The second mistake is forgetting that requires is not transitive. If module A requires module B and module B requires module C, A cannot read C unless B declares "requires transitive C" or A adds its own "requires C". This often surfaces as a confusing "package X is declared in module Y but module A does not read Y" error.

The third mistake is using opens too widely. Frameworks like Hibernate, Spring, and Jackson use reflection to set private fields, which means the modules that hold your domain classes need "opens" directives. The mistake is writing "opens com.example.app;" which exposes every package to reflective access, defeating the point of modularity. Prefer "opens com.example.app.model;" to limit exposure to the package that actually needs reflection.

The fourth mistake is placing non-exported classes on the classpath instead of the module path. The module system only enforces access rules when modules are loaded via -p or --module-path; if the same classes are placed on the classpath with -cp, they become part of the unnamed module and all access checks are bypassed. Production deployments should commit to one mode, not mix the two.

The fifth mistake is leaving the module-info.java out of the published JAR. If you ship a JAR with the module-info.class omitted, downstream consumers on the module path will treat the JAR as an automatic module whose name is derived from the JAR filename, which is fragile. Always include the compiled module-info.class in the published JAR.

Real-World Applications

The Jigsaw module system is the foundation of the modern JDK itself. As of Java 9, the JDK is split into roughly a hundred modules: java.base (core java.lang, java.util), java.sql (JDBC), java.desktop (AWT and Swing), java.net.http (the Java 11 HTTP client), and so on. Custom runtime images can be built with jlink, which produces a stripped JVM containing only the modules your application requires; for a server application that uses no Swing, this can shrink the runtime from 200 MB to 50 MB.

In the wider ecosystem, modular JARs are common in library code that wants to ship an API package separately from an internal implementation. Spring Framework 6 ships module-info.java for every spring-* JAR, making it usable both on the classpath and on the module path. Logback, JUnit 5, and Mockito all include module-info.java. JetBrains IntelliJ IDEA and Eclipse OpenJ9 both consume the module path natively. Studying java 9 modules jigsaw is therefore the prerequisite for understanding jlink, custom runtime images, and the modern packaging story that ships with jpackage since Java 14. The java 9 modules jigsaw story also shapes how the JDK itself is split into the roughly one hundred modules that ship with every modern JDK.

Conclusion

We showed the module-info.java file with requires and exports directives, the difference between exported api packages and unexported internal packages, how the module path differs from the classpath, and how reflective access is denied at runtime without an opens directive. Jigsaw is the foundation of the modular JDK and of every modern library that wants strong encapsulation. The natural next topics to study are jlink for custom runtime images, the unnamed and automatic module fallbacks, and the Java 9 ServiceLoader uses and provides directives that let modules consume and publish service implementations across module boundaries.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments