Sub topic 11
Reflection and the opens directive
This chapter assumes you know how exports and requires work, what strong encapsulation means, and the basics of java.lang.reflect. You should also know what setAccessible(true) does on the classpath.
Why reflection needs its own rule
exports controls compile-time and run-time access to the public members of public types. Reflection is different. Frameworks such as Jackson, Hibernate, and Spring often read private fields, call private constructors, and instantiate classes by name.
Before Java 9, setAccessible(true) could open up any member of any class. Strong encapsulation removed that. In a named module, reflection follows two rules:
- Code can reflectively access
publicmembers ofpublictypes only in packages that are exported (to the caller's module). - Code can reflectively access non-public members (using
setAccessible(true)) only in packages that are opened (to the caller's module).
An opens directive grants "deep reflection". This means access at run time to all members of all types in the package, including private ones. It does not affect compilation. Your source code still cannot name a non-exported type.
The three forms of opens
module com.example.library {
exports com.example.library.api;
opens com.example.library.model; // open to every module
opens com.example.library.config to com.fasterxml.jackson.databind; // qualified open
}You can also open the whole module:
open module com.example.library {
requires java.sql;
exports com.example.library.api;
}An open module opens every package at run time. It cannot contain opens directives, because they would be redundant. It is convenient during migration. It also gives up the encapsulation you adopted modules to get.
| Directive | Compile-time access | Run-time public access | Run-time private access |
|---|---|---|---|
| `exports p` | Yes | Yes | No |
| `opens p` | No | Yes | Yes |
| `exports p` and `opens p` | Yes | Yes | Yes |
| neither | No | No | No |
A package that is only opened is accessible to reflection but not to compiled code. Internally, opens implies the package's public types can be loaded and their members reflected on.
A worked example
This example has a model package that a separate app module inspects reflectively. First the library module:
// src/com.example.library/module-info.java
module com.example.library {
exports com.example.library.api;
}
// src/com.example.library/com/example/library/model/Person.java
package com.example.library.model;
public class Person {
private String name = "Ada";
}Now the app, which reads the private field:
// src/com.example.app/module-info.java
module com.example.app {
requires com.example.library;
}
// src/com.example.app/com/example/app/Main.java
package com.example.app;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws Exception {
Class<?> type = Class.forName("com.example.library.model.Person");
Object person = type.getDeclaredConstructor().newInstance();
Field field = type.getDeclaredField("name");
field.setAccessible(true);
System.out.println(field.get(person));
}
}Because com.example.library.model is neither exported nor opened, the call to getDeclaredConstructor().newInstance() fails with an IllegalAccessException. If it got past that, setAccessible(true) would throw InaccessibleObjectException. The message names the package and the module:
java.lang.reflect.InaccessibleObjectException: Unable to make field private java.lang.String
com.example.library.model.Person.name accessible: module com.example.library does not
"opens com.example.library.model" to module com.example.appThe fix belongs in the library's descriptor:
module com.example.library {
exports com.example.library.api;
opens com.example.library.model to com.example.app;
}Choosing between exports, opens, and qualified forms
Use these criteria:
- If other code compiles against the package, use
exports. - If only a framework touches it through reflection, use
opens, and qualify it withtowhen you know the framework's module name. - If the code is shared with a named module that is automatic, qualify with that module's automatic name.
- Reserve
open modulefor short-term migration or for modules that are essentially data models.
Qualifying matters because an unqualified opens allows any module, including a malicious or buggy one, to read private state.
A common edge case: a qualified opens ... to X is silently skipped, with only a compiler lint warning, if module X is not found at compile time. Check the warning output. This is correct behavior, because the target may be resolved only at run time.
Reflection on JDK internals
The JDK itself is made of modules that do not open their internal packages. Since Java 16, --illegal-access no longer exists, and strong encapsulation of JDK internals is always on, with the exception of the command-line flags below. Code that worked on Java 8 by reflecting into java.lang or sun.misc internals can fail with InaccessibleObjectException.
You can open a JDK package at launch time:
# Allow classpath code (the unnamed module) deep reflection into java.lang
java --add-opens java.base/java.lang=ALL-UNNAMED -cp app.jar com.example.Main
# Open a package to a specific named module
java --add-opens java.base/java.lang=com.example.app \
--module-path out -m com.example.app/com.example.app.Main--add-exports is the related flag that makes a package accessible to compiled code and reflection on public members. --add-opens is the one to use when the error mentions setAccessible.
Reflection across your own modules
Two more rules help with debugging:
- Reading a module's reflective view still requires readability. Your module must read the module you are reflecting on, or you can call
Module.addReads, which is rarely needed. - Frameworks that load classes by name need the target module in the resolved graph. If nothing
requiresit, add it with--add-modules.
You can query and adjust state at run time:
Module module = Person.class.getModule();
String pkg = Person.class.getPackageName();
System.out.println(module.isOpen(pkg)); // opened to everyone?
System.out.println(module.isOpen(pkg, Main.class.getModule())); // opened to this caller?
System.out.println(module.isExported(pkg));A module can open a package to another module at run time only if it is itself the caller, with Module.addOpens. This design means a module can grant access from inside, but outsiders cannot force it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `InaccessibleObjectException` naming your package | Framework needs private access and the package is not opened | Add `opens pkg to framework.module` |
| Same error naming a `java.base` package | Library uses JDK internals | Upgrade the library, or add `--add-opens` |
| `IllegalAccessException` on `newInstance` | Package is not exported or opened | Open or export it |
| Framework cannot find your classes at all | Module not in the module graph | Check `requires` or `--add-modules` |
| `opens` has no effect on the unnamed module | Classpath code is not subject to it | The unnamed module opens everything already |
Exercise
A module com.shop.orders has a package com.shop.orders.entity with private fields. Hibernate, running as the named module org.hibernate.orm.core, must set those fields reflectively. No other module should compile against entity. Which directive do you write, and why not exports?
Show answer
Write opens com.shop.orders.entity to org.hibernate.orm.core;. Reflection on private fields needs the package opened, and the qualified form limits that access to Hibernate. exports would let any module compile against the package and would not grant access to private members.
Exercise
Your app runs on the classpath and fails with InaccessibleObjectException: ... module java.base does not "opens java.lang" to unnamed module @1a2b3c. What command-line flag fixes it, and what is the better long-term fix?
Show answer
Run with --add-opens java.base/java.lang=ALL-UNNAMED. The better long-term fix is to upgrade or replace the library that reflects into java.lang, so no JDK internals are needed.