Modular JARs and Reflective Access in Java: opens and open modules
Package Java modules as modular JARs with jar, --module-version and a main class, then learn why deep reflection fails across modules and fix it with opens, open modules, resource access rules and MethodHandles.Lookup.
kvi5hnuCode Sprout team member8 min readOn this page
Compiling modules into directory trees is fine for learning, but real applications are deployed as JAR files. This article packages modules as modular JARs. It then tackles the biggest practical change modules bring to libraries: reflection can no longer reach private members of classes in other modules unless the owning module allows it.
Modular JARs
A modular JAR is an ordinary JAR file with a module-info.class at its root. Compile with -d into a separate directory, then use jar -C to collect the files from there:
javac -d classes/com.example.greet com.example.greet/module-info.java \
com.example.greet/com/example/greet/Greeter.java \
com.example.greet/com/example/greet/internal/GreeterImpl.java
jar --create --file com.example.greet-1.0.jar --module-version 1.0 -C classes/com.example.greet .
With Maven, Gradle or Ant, keep building JARs as usual. As long as module-info.class is included, the result is a modular JAR. Put it on the module path and the module is loaded.
You can record a main class with -e, and then launch by module name alone:
jar -c -f hello.jar -e com.example.hello.HelloWorld -C classes/hello .
java -p com.example.greet-1.0.jar:hello.jar -m hello
--module-version stores a version string. As article 111 explained, JPMS doesn't use versions to resolve modules, but tools and frameworks can read them, for example with Greeter.class.getModule().getDescriptor().rawVersion(). Add the version to the JAR file name too. jar --describe-module --file x.jar prints a JAR's module declaration, including the packages it contains but doesn't export.
Other points about modular JARs:
- Classes of one package spread over several JARs (a split package) were always a bad idea, and with modules they're impossible.
- The module counterpart of a class loader is a layer. The JVM loads the JDK and your application modules into the boot layer, and application servers and plugin systems can create further layers with
ModuleLayer. Such programs may also take versions into account. - To experiment with a module in JShell:
jshell --module-path com.example.greet-1.0.jar --add-modules com.example.greet.
Modules and reflective access
Article 54 showed that reflection can read and write private fields:
Field f = obj.getClass().getDeclaredField("salary");
f.setAccessible(true);
double value = f.getDouble(obj);
f.setDouble(obj, value * 1.1);
Many libraries depend on this deep reflection. Object-relational mappers such as JPA/Hibernate persist objects automatically, and JSON or XML binders such as Jackson, JSON-B and JAXB convert objects to text. In the modular world, setAccessible(true) fails when the class is in a module that doesn't permit it.
Suppose a utility module com.example.util contains a FieldDumper that prints an object's fields using reflection, and a module places contains a Country class with private name and area fields. Dumping a Country fails:
java.lang.reflect.InaccessibleObjectException: Unable to make field private java.lang.String
com.example.places.Country.name accessible: module places does not "opens com.example.places"
to module com.example.util
In pure theory, poking at private fields violates encapsulation. But object mapping and data binding are so common that the module system has to support them, and it does so on the owner's terms.
opens
With opens, a module opens a package for deep reflection at runtime. All members of all its classes, including private ones, become reflectively accessible:
module places {
requires com.example.util;
opens com.example.places;
}
Now FieldDumper works. opens doesn't export the package at compile time. Other modules still can't write code against it. It only permits reflection. Article 115 shows opens ... to for opening to specific modules only, such as your persistence framework.
Open modules
A whole module can be declared open:
open module places {
requires com.example.util;
}
An open module grants runtime reflective access to all its packages, as if every package were opened. At compile time, only explicitly exported packages are accessible. Open modules combine compile-time module checking with the classic permissive runtime behavior, which is handy for applications built on frameworks such as Spring or Hibernate.
Resources
Resources can be loaded with Class.getResourceAsStream and, since Java 9, Module.getResourceAsStream. A resource stored in a directory that matches a package of a module (such as com/example/places/capitals.txt) is encapsulated like that package. Other modules can read it only if the package is opened to them. Resources in other directories, such as a top-level notes.txt, as well as class files and META-INF entries, can be read by anyone. The demo shows the package resource coming back as null until the package is opened.
Handing over a Lookup
Libraries can also use variable handles instead of Field. A VarHandle reads or writes a particular field of instances of a class, but to get one for a private field, the library needs a MethodHandles.Lookup with the right access:
public Object getFieldValue(Object obj, String fieldName, MethodHandles.Lookup lookup)
throws ReflectiveOperationException {
Class<?> cl = obj.getClass();
Field field = cl.getDeclaredField(fieldName);
VarHandle handle = MethodHandles.privateLookupIn(cl, lookup).unreflectVarHandle(field);
return handle.get(obj);
}
MethodHandles.lookup() returns an object that carries the access rights of its caller. If code inside places creates the lookup and passes it to the library, the library can access places's private fields even though the package isn't opened. That's how a module can grant access deliberately and selectively. The demo does this in all three variants. The practical difficulty is distributing such permissions with little hassle, which is why most frameworks still ask you to opens your packages.
A complete example
The demo builds two modular JARs with the jar tool (one with a version, one with a main class), describes one, and runs the application by module name. It then runs the same places program against com.example.util three times: with a closed package (deep reflection fails, the package resource is hidden, but the handed-over Lookup works), with opens, and as an open module.
import java.io.*;
import java.lang.module.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
public class Solution {
static Path root;
static void source(String path, String text) throws IOException {
Path p = root.resolve("src").resolve(path);
Files.createDirectories(p.getParent());
Files.writeString(p, text);
}
static String clean(String s) {
return s.replace(root.toUri().toString(), "").replace(root.toString() + File.separator, "")
.replace(root.toString(), "").replace(File.separatorChar, '/');
}
static void tool(String name, String... args) {
var out = new StringWriter();
int rc = ToolProvider.findFirst(name).orElseThrow().run(new PrintWriter(out, true), new PrintWriter(out, true), args);
out.toString().lines().forEach(l -> System.out.println(" " + clean(l)));
if (rc != 0) System.out.println(" " + name + " failed");
}
static void java(String... args) throws IOException, InterruptedException {
var cmd = new ArrayList<String>(List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString()));
cmd.addAll(List.of(args));
System.out.println(" $ java " + clean(String.join(" ", args)).replace(File.pathSeparator, ":"));
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
new String(p.getInputStream().readAllBytes()).lines()
.filter(l -> !l.strip().startsWith("at ")) // keep messages, drop stack frames
.forEach(l -> System.out.println(" " + clean(l)));
p.waitFor();
}
static String p(String rel) { return root.resolve(rel).toString(); }
static String mp(String... rels) { return String.join(File.pathSeparator, Arrays.stream(rels).map(Solution::p).toList()); }
static void compile(String outDir, String modulePath, String... files) {
var args = new ArrayList<String>(List.of("-d", p(outDir)));
if (modulePath != null) { args.add("-p"); args.add(modulePath); }
for (String f : files) args.add(p("src/" + f));
tool("javac", args.toArray(String[]::new));
}
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("mods");
System.out.println("-- building modular JARs --");
source("com.example.greet/module-info.java", "module com.example.greet { exports com.example.greet; }\n");
source("com.example.greet/com/example/greet/Greeter.java", """
package com.example.greet;
public interface Greeter {
static Greeter newInstance() { return new com.example.greet.internal.GreeterImpl(); }
String greet(String subject);
}
""");
source("com.example.greet/com/example/greet/internal/GreeterImpl.java", """
package com.example.greet.internal;
public class GreeterImpl implements com.example.greet.Greeter {
public String greet(String subject) { return "Hello, " + subject + "!"; }
}
""");
compile("classes/com.example.greet", null, "com.example.greet/module-info.java",
"com.example.greet/com/example/greet/Greeter.java", "com.example.greet/com/example/greet/internal/GreeterImpl.java");
Files.createDirectories(root.resolve("jars"));
tool("jar", "--create", "--file", p("jars/com.example.greet-1.0.jar"), "--module-version", "1.0",
"-C", p("classes/com.example.greet"), ".");
source("hello/module-info.java", "module hello { requires com.example.greet; }\n");
source("hello/com/example/hello/HelloWorld.java", """
package com.example.hello;
import com.example.greet.Greeter;
public class HelloWorld {
public static void main(String[] args) {
System.out.println(Greeter.newInstance().greet("Modular JAR"));
System.out.println("greet module version: "
+ Greeter.class.getModule().getDescriptor().rawVersion().orElse("none"));
}
}
""");
compile("classes/hello", p("jars"), "hello/module-info.java", "hello/com/example/hello/HelloWorld.java");
tool("jar", "-c", "-f", p("jars/hello.jar"), "-e", "com.example.hello.HelloWorld", "-C", p("classes/hello"), ".");
System.out.println(" jar --describe-module:");
tool("jar", "--describe-module", "--file", p("jars/com.example.greet-1.0.jar"));
java("-p", mp("jars/com.example.greet-1.0.jar", "jars/hello.jar"), "-m", "hello"); // main class comes from the JAR
System.out.println("-- reflection into a module that does not open its package --");
source("com.example.util/module-info.java", "module com.example.util { exports com.example.util; }\n");
source("com.example.util/com/example/util/FieldDumper.java", """
package com.example.util;
import java.io.*;
import java.lang.invoke.*;
import java.lang.reflect.*;
public class FieldDumper {
/** Lists the fields of an object using deep reflection. */
public String toString(Object obj) throws IllegalAccessException {
var sb = new StringBuilder(obj.getClass().getSimpleName()).append('[');
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true); // needs the package to be open
sb.append(f.getName()).append('=').append(f.get(obj)).append(';');
}
return sb.append(']').toString();
}
/** Reads a field through a Lookup supplied by the owning module. */
public Object field(Object obj, String name, MethodHandles.Lookup lookup) throws ReflectiveOperationException {
Class<?> cl = obj.getClass();
VarHandle h = MethodHandles.privateLookupIn(cl, lookup).unreflectVarHandle(cl.getDeclaredField(name));
return h.get(obj);
}
public String resource(Module m, String name) throws IOException {
try (InputStream in = m.getResourceAsStream(name)) {
return in == null ? "null (not accessible)" : new String(in.readAllBytes()).strip();
}
}
}
""");
compile("ex/com.example.util", null, "com.example.util/module-info.java", "com.example.util/com/example/util/FieldDumper.java");
String country = """
package com.example.places;
public class Country {
private String name;
private double area;
public Country(String name, double area) { this.name = name; this.area = area; }
}
""";
String demo = """
package com.example.places;
import com.example.util.FieldDumper;
import java.lang.invoke.MethodHandles;
public class Demo {
public static void main(String[] args) throws Exception {
var belgium = new Country("Belgium", 30510);
var dumper = new FieldDumper();
System.out.println("via a Lookup we hand over: name=" + dumper.field(belgium, "name", MethodHandles.lookup()));
System.out.println("top-level resource: " + dumper.resource(Demo.class.getModule(), "notes.txt"));
System.out.println("package resource: " + dumper.resource(Demo.class.getModule(), "com/example/places/capitals.txt"));
System.out.println(dumper.toString(belgium));
}
}
""";
Map<String, String> variants = new LinkedHashMap<>();
variants.put("closed", "module places {\n requires com.example.util;\n}\n");
variants.put("opens", "module places {\n requires com.example.util;\n opens com.example.places;\n}\n");
variants.put("open module", "open module places {\n requires com.example.util;\n}\n");
int n = 0;
for (var v : variants.entrySet()) {
String dir = "v" + (n++);
System.out.println("-- places module: " + v.getKey() + " --");
v.getValue().lines().forEach(l -> System.out.println(" | " + l));
source(dir + "/module-info.java", v.getValue());
source(dir + "/com/example/places/Country.java", country);
source(dir + "/com/example/places/Demo.java", demo);
compile("ex/" + dir, p("ex/com.example.util"), dir + "/module-info.java",
dir + "/com/example/places/Country.java", dir + "/com/example/places/Demo.java");
Files.writeString(root.resolve("ex/" + dir + "/notes.txt"), "anyone may read this");
Files.writeString(root.resolve("ex/" + dir + "/com/example/places/capitals.txt"), "Brussels");
java("-p", mp("ex/com.example.util", "ex/" + dir), "-m", "places/com.example.places.Demo");
}
System.out.println("-- the module version through the API --");
ModuleDescriptor d = ModuleFinder.of(root.resolve("jars")).find("com.example.greet").orElseThrow().descriptor();
System.out.println(" " + d.toNameAndVersion() + ", main class of hello.jar: "
+ ModuleFinder.of(root.resolve("jars")).find("hello").orElseThrow().descriptor().mainClass().orElse("none"));
try (var walk = Files.walk(root)) { walk.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete()); }
}
}
-- building modular JARs --
jar --describe-module:
com.example.greet@1.0 jar:jars/com.example.greet-1.0.jar!/module-info.class
exports com.example.greet
requires java.base mandated
contains com.example.greet.internal
$ java -p jars/com.example.greet-1.0.jar:jars/hello.jar -m hello
Hello, Modular JAR!
greet module version: 1.0
-- reflection into a module that does not open its package --
-- places module: closed --
| module places {
| requires com.example.util;
| }
$ java -p ex/com.example.util:ex/v0 -m places/com.example.places.Demo
via a Lookup we hand over: name=Belgium
top-level resource: anyone may read this
package resource: null (not accessible)
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private java.lang.String com.example.places.Country.name accessible: module places does not "opens com.example.places" to module com.example.util
-- places module: opens --
| module places {
| requires com.example.util;
| opens com.example.places;
| }
$ java -p ex/com.example.util:ex/v1 -m places/com.example.places.Demo
via a Lookup we hand over: name=Belgium
top-level resource: anyone may read this
package resource: Brussels
Country[name=Belgium;area=30510.0;]
-- places module: open module --
| open module places {
| requires com.example.util;
| }
$ java -p ex/com.example.util:ex/v2 -m places/com.example.places.Demo
via a Lookup we hand over: name=Belgium
top-level resource: anyone may read this
package resource: Brussels
Country[name=Belgium;area=30510.0;]
-- the module version through the API --
com.example.greet@1.0, main class of hello.jar: com.example.hello.HelloWorld
Common questions
What is the difference between exports and opens?
exports allows other modules to compile against and use the package's public types. opens allows deep reflection at runtime, including private members, but grants no compile-time access. A package can be both exported and opened.
Why does Jackson or Hibernate fail with InaccessibleObjectException in my modular app?
The framework uses setAccessible(true) on your classes, and your module doesn't open the package. Add opens com.example.model;, or better, opens com.example.model to com.fasterxml.jackson.databind; to open it only to that framework.
Should I declare my application module as open?
It's a pragmatic choice for applications built on frameworks that reflect over many packages, such as Spring. You keep compile-time module checks but give up runtime encapsulation. Libraries should open only the packages they need to.
How do I set a main class so I can run a modular JAR by module name?
Pass --main-class (or -e) to the jar tool. Then java -p mods -m com.example.app starts it without naming the class.
Can a module read resources from another module?
Resources in a non-package directory, such as META-INF, or in files ending in .class, are not encapsulated. Resources inside a package directory are encapsulated like the package, so another module can read them only if the package is opened to it.
API reference
| Item | Description |
|---|---|
jar --create --file f.jar [--module-version v] [-e main.Class] -C dir . | creates a (modular) JAR |
jar --describe-module --file f.jar | prints the module declaration in a JAR |
opens package.name; | allows deep reflection on the package at runtime |
open module name { ... } | opens all packages of the module at runtime |
Optional<String> ModuleDescriptor.rawVersion(), Optional<String> mainClass() | version and main class recorded in module-info.class |
InputStream Module.getResourceAsStream(String name) | reads a module resource; package resources need the package opened |
static MethodHandles.Lookup MethodHandles.lookup(), privateLookupIn(Class<?> target, Lookup caller) | lookups carrying access rights; unreflectVarHandle(Field) |
Summary
- A modular JAR is a JAR with
module-info.classat its root.jarcan record a module version (ignored for resolution) and a main class, sojava -p ... -m moduleis enough to start it. - Deep reflection (
setAccessible) into another module throwsInaccessibleObjectExceptionunless the package is opened. Exported packages allow only public access. opens pkgpermits reflection on one package, andopen modulepermits it on all packages, while compile-time access still followsexports.- Resources in package directories are encapsulated like their package. Passing a
MethodHandles.Lookuplets a module grant access selectively.
Practice Questions
What makes a JAR file a modular JAR?
It contains a module-info.class at its root. Placed on the module path, it's loaded as a named module with the declared requirements and exports.
Does the module system choose between com.example.greet-1.0.jar and com.example.greet-2.0.jar by version?
No. JPMS ignores versions when resolving modules. If both JARs are in the same module-path directory, startup fails with a FindException (two modules with the same name). If they're in different module-path entries, the first one wins and the other is silently ignored. Either way the version is only metadata; choosing versions is the build tool's job.
What is the difference between exports and opens?
exports gives compile-time and runtime access to the public and protected API of a package. opens gives runtime reflective access to all members, including private ones, but no compile-time access. A package can be both exported and opened.
A JSON library throws InaccessibleObjectException when serializing your module's classes. What are your options?
Add opens your.package; (or opens your.package to the.library.module;) to module-info.java, or declare the module open. As a temporary workaround from the command line, use --add-opens (article 114).
Why can a library read a private field when the owning module passes MethodHandles.lookup()?
The lookup object carries the access rights of the code that created it, here code in the owning module, which may access its own private members. privateLookupIn with that lookup yields a lookup with private access to the class, so the library can obtain a VarHandle for the field.
Previous: Java Module requires and exports: Dependencies and Exported Packages
Next: Java Automatic Modules, the Unnamed Module and Migration Flags
Related reading
- Java Module requires and exports: Dependencies and Exported Packages
- Java Modules Introduction: The Module Concept and a Hello World Module
- Your First Java Program Explained: Classes, main, Statements and Comments
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.