Sub topic 7
Private members, setAccessible, and Java modules
This chapter assumes you can already get a Class object and call getDeclaredField, getDeclaredMethod, Field.get and Method.invoke. It also assumes you know what a package is and how to compile and run a Java program from the command line. Here you will see why reflection fails on private members by default, how setAccessible changes that, and where the Java 9+ module system stops it.
Access checks apply to reflection too
Reflection does not bypass the access rules of the language by default. When you call Field.get, Field.set, Method.invoke or Constructor.newInstance, the JVM checks whether the calling class could have used that member in ordinary source code. If it could not, the call throws IllegalAccessException.
Two lookup families interact with this rule:
getField,getMethodandgetConstructorreturn only public members, including inherited public ones.getDeclaredField,getDeclaredMethodandgetDeclaredConstructorreturn any member declared in that exact class, whatever its modifiers, but not inherited members.
Finding a private member is therefore easy. Using it is the step that is checked.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Vault {
private String secret = "swordfish";
private static final int LIMIT = 3;
private int attempts() {
return 7;
}
}
public class PrivateDemo {
public static void main(String[] args) throws Exception {
Vault v = new Vault();
Field secret = Vault.class.getDeclaredField("secret");
try {
secret.get(v);
} catch (IllegalAccessException e) {
System.out.println("denied: " + e.getMessage());
}
secret.setAccessible(true);
System.out.println(secret.get(v));
secret.set(v, "opensesame");
System.out.println(secret.get(v));
Method attempts = Vault.class.getDeclaredMethod("attempts");
attempts.setAccessible(true);
System.out.println(attempts.invoke(v));
Field limit = Vault.class.getDeclaredField("LIMIT");
limit.setAccessible(true);
System.out.println(limit.get(null));
try {
limit.set(null, 9);
} catch (IllegalAccessException e) {
System.out.println("static final: " + e.getMessage());
}
}
}The first get fails because PrivateDemo is a different class from Vault, and the exception message names the caller and the private modifier. After setAccessible(true) the same call succeeds. The last lines show a limit: setAccessible lets you write a non-static final field, but a static final field still throws IllegalAccessException on set. Treat even the instance final case as a hack. The JIT compiler may have inlined the old value, and records and hidden classes refuse it outright.
What setAccessible does
AccessibleObject.setAccessible(boolean) is the superclass method behind Field, Method and Constructor. Passing true turns off the language-level access check for that one reflective object. Four details cause most of the confusion:
- The flag lives on the
Field,MethodorConstructorinstance you call it on.getDeclaredFieldreturns a new copy each time, so setting the flag on one copy does not affect another lookup. - The flag removes the
private, package-private andprotectedchecks. It does not change the member's modifiers. - Since Java 9,
setAccessiblecan itself fail. It throwsInaccessibleObjectException, an unchecked exception, when the module system forbids the request. trySetAccessible()(Java 9) returnsfalseinstead of throwing.canAccess(Object)(Java 9) tells you whether the caller can use the member right now. It replaces the deprecatedisAccessible(), which only reported the flag.
Prefer trySetAccessible in library code that must degrade gracefully, and setAccessible when failure should stop the program with a clear error.
Modules add a second check
Before Java 9, setAccessible(true) worked on almost anything. The module system added strong encapsulation: a module decides which of its packages other modules may see, and in what way. Two directives in module-info.java matter here:
| Directive | Compile-time use of public types | Runtime reflection on public members | Runtime reflection on private members (`setAccessible`) |
|---|---|---|---|
| none (package is not exported) | No | No | No |
| `exports p` | Yes | Yes | No |
| `opens p` | No (unless also exported) | Yes | Yes |
| `open module m` (opens every package) | No (unless exported) | Yes | Yes |
The key point is that exports gives you the public API only. Deep reflection, meaning access to private members, needs opens. A module declaration that grants both looks like this:
module app.model {
exports com.example.model;
opens com.example.model.entity to com.fasterxml.jackson.databind;
}Here the entity package is open only to one named module. Without the to clause, it would be open to every module.
The check is based on the module of the code that calls setAccessible, not the module of the code that eventually uses the result. Code on the classpath lives in the unnamed module, and a named module's opens to everyone includes it.
Reflecting on the JDK itself
The JDK's own modules, such as java.base, export their public API and open almost nothing. Reaching into private JDK state is where modules bite hardest.
import java.lang.reflect.Field;
public class OpenDemo {
public static void main(String[] args) throws Exception {
Field value = String.class.getDeclaredField("value");
boolean ok = value.trySetAccessible();
System.out.println("accessible: " + ok);
}
}The result depends on the Java version:
- Java 9 to 15: the default was
--illegal-access=permit. For classpath code this printsaccessible: trueafter a one-time warning on standard error about an illegal reflective access. - Java 16: the default became
deny, so the same code printsaccessible: false. - Java 17 and later: the
--illegal-accessoption is gone and strong encapsulation of JDK internals is always on.
Code that worked on Java 8 or 11 by reflecting into JDK internals therefore often breaks after an upgrade. Calling setAccessible(true) there throws InaccessibleObjectException with a message such as Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module. The message names the module, the package and the caller, which is exactly what you need for the fix.
Granting access from outside
When you do not control the target module, you can open a package at launch time:
java --add-opens java.base/java.lang=ALL-UNNAMED -cp app.jar com.example.MainThe syntax is --add-opens module/package=target, where the target is a module name or ALL-UNNAMED for all classpath code. The related --add-exports flag only exposes public API. In an executable JAR you can set Add-Opens in the manifest instead. These flags are a workaround for legacy libraries. They do not fix your own code, so prefer a supported API where one exists.
For your own modules, the fix belongs in module-info.java: add an opens line, ideally qualified with to, for the framework that needs it.
Choosing a policy
- Prefer public APIs, getters and constructors when they exist. Private members are not part of a class's contract and can change in any release.
- Use
setAccessiblefor frameworks that must populate fields, such as serialization, dependency injection and validation, and open only the packages that need it. - Treat
--add-opensas a temporary bridge with a written reason. - Call
setAccessibleonce, close to where you look the member up, and cache theFieldorMethodobject. - A
SecurityManager, if one is installed, can also denysetAccessiblewith aSecurityException. This is rare in modern applications.
Exercise
A library in a named module calls field.setAccessible(true) on a private field of a class in your module app.model. Your module-info.java has exports com.example.model; and nothing else, and the field is in that package. What happens, and what is the narrowest change that fixes it?
Show answer
The call throws InaccessibleObjectException, because exports only makes public members of public types visible. Private members need the package to be open. The narrowest fix is to add opens com.example.model to <library.module.name>; to module-info.java, which opens the package only to the module that needs it. Using opens com.example.model; without to would also work but opens it to every module.
Exercise
Why can the line Field f1 = C.class.getDeclaredField("x"); f1.setAccessible(true); Field f2 = C.class.getDeclaredField("x"); f2.get(obj); still throw IllegalAccessException when x is private and the code runs in another class?
Show answer
getDeclaredField returns a new Field object on every call, and the accessible flag is stored on the instance. f1 is accessible but f2 is a fresh copy with the flag unset, so its access check fails. Call setAccessible(true) on f2, or keep using f1.