Lesson · Reflection, Proxies & Method Handles
Access, Encapsulation & Safety
11 min readAccess, Encapsulation & Safety
setAccessible(true) suppresses the language's access check on one reflected object. It does not overrule the module system, and it cannot make a static final field writable. Knowing exactly what the flag unlocks is the difference between a working workaround and a permanent hole.
The upgrade that broke nothing in your code
The report reads like this: an application moved to JDK 17, and a startup step that had worked for years now fails with InaccessibleObjectException and a message about a module that does not open a package. Nothing in the application changed. The JDK did.
The failing line is reflective. Some library asks to read a private field or invoke a protected method with setAccessible(true), and from JDK 16 the default answer to that request became no (JEP 396). From JDK 17 the ability to relax the answer for the whole JDK via --illegal-access was removed (JEP 403). The flag itself still works where it ever did; what changed is which packages are open.
// the shape that started failing on JDK 16 and later, written long before it did Field field = SomeJdkClass.class.getDeclaredField("somePrivateField"); field.setAccessible(true); // InaccessibleObjectException on JDK 17+ Object value = field.get(instance);
The flag did not break; the default changed. setAccessible is the same call it always was. What moved is the module system's answer to it.
What setAccessible(true) actually unlocks
Start with a precise model. setAccessible(true) sets a boolean on one reflected object (Field, Method and Constructor all extend AccessibleObject). From then on that object does not enforce the Java language access rules when it is used: a private field can be read, a private field can be written, a private method can be invoked, a private constructor can be called.
Three things the flag does not do. It does not make the member public to other code, because the flag lives on your object rather than on the member. It does not bypass the module boundary, which decides whether the flag may be set at all. And it cannot grant write access to a final field whose declaring class is a record or a hidden class, or to any static final field, because those are non-modifiable by construction; on those fields the flag only unlocks reads.
| Member | After setAccessible(true) | Still refused |
|---|---|---|
| private instance field, read | allowed, if the module lets you set the flag | nothing: this is the case the flag exists for |
| private instance field, write | allowed for a non-final field | final fields of records and hidden classes, whatever you do |
| private method, invoke | allowed, with the same module condition | nothing beyond that condition |
| private constructor | allowed, with the same module condition | nothing beyond that condition |
| static final field, write | read only | write: static final fields are non-modifiable, flag or no flag |
| record component field, write | read only | write: fields of a record class are non-modifiable too |
The flag is per reflected object, not per member. Call it on the Field you hold and that one Field stops checking; the member, and everyone else, stay exactly as private as before.
Strong encapsulation: JDK 16 and JDK 17
Strong encapsulation is the name for the default that arrived with modules and then hardened two releases later. Through JDK 15 the JDK still permitted illegal reflective access to packages that had existed in JDK 8, behind a warning and the option --illegal-access=permit. JDK 16 (JEP 396) changed the default of that option to deny. JDK 17 (JEP 403) made the option obsolete: using it now only prints a warning, and there is no longer a single switch that reopens the JDK.
- JDK 16 (JEP 396): illegal reflective access to JDK internals denied by default, with
--illegal-access=permitstill available for one release. - JDK 17 (JEP 403):
--illegal-accesshas no effect beyond a warning, so per-package--add-opensand--add-exportsare the only keys left. - Two failure types, two situations:
InaccessibleObjectExceptionfromsetAccessible, andIllegalAccessErrorwhen compiled code touches a class from a package that is not exported at all. - Two packages stayed open on purpose:
sun.miscandsun.reflectare still exported and opened by thejdk.unsupportedmodule, because the ecosystem leaned on them so heavily; that is a compatibility concession, not an endorsement.
One rule replaced a category of workarounds. From JDK 17 there is no JDK-wide escape hatch, only per-package keys that you write down, name a reason for, and can remove later.
Modules: exports, opens, and the add-opens key
The module system has two doors, and reflection only cares about one of them. exports means code in other modules may compile against the package and use its public types. opens means code in other modules may use deep reflection on it, so setAccessible is allowed. A package can be exported and not opened, opened and not exported, both, or neither.
From the caller's side there are two flags, and they are not synonyms. --add-exports com.acme.core/com.acme.core.internal=com.acme.client lets you compile and link against a package that is not exported. --add-opens com.acme.core/com.acme.core.internal=com.acme.client lets reflection look inside, which is what a failing setAccessible is asking for. The value ALL-UNNAMED stands in for everything on the class path.
When you own the target, the honest fix is a directive rather than a flag: opens com.acme.core.internal to com.acme.client; in the module descriptor, or the qualified exports ... to ... when only one module should see the package. The Java Platform Module System lesson owns the descriptor itself; the reflection-facing rule is the one above.
| Door | What it permits | Caller option |
|---|---|---|
| exports pkg | compiling against public types and calling public members | --add-exports when you cannot change the target module |
| opens pkg | deep reflection: setAccessible on any member of the package | --add-opens, the flag behind every unable-to-make-accessible fix |
| neither | public members are unreachable for compile and call too | --add-opens or --add-exports for that exact package; there is no whole-JDK switch |
- Classpath code is the open case: the unnamed module is open to all modules and
setAccessiblealways succeeds against it, which is why the same code works in a plain jar and fails inside a modular application. - The veto is always the declaring module's: the question the runtime asks is whether that module opens the package to your module, never whether your module would like access.
- Declare opens one package at a time, and prefer the qualified form so the opening lands on a caller you can name.
exports is for compiling against; opens is for looking inside. Add the flag that matches the need, and prefer the descriptor directive over the launcher flag when you own the module.
Encapsulation lab · attempt x caller context
pick one of eachDifferent package, but both classes sit in the unnamed module, which is open to all modules, so the flag can be set.
Why the framework broke, and the fix that spread
The famous error of the JDK 17 migration belongs here. A framework asks to reach a member of java.lang.Class or java.lang.ClassLoader that was never meant to be reached, typically to define a generated subclass in the application's loader, and the runtime answers with a message naming both sides: the member it will not make accessible, and the module that does not open the package to the caller, usually the unnamed module.
Frameworks that generate classes, Spring's proxy layer and Hibernate's enhancers among them, moved to the supported route for exactly this: MethodHandles.Lookup::defineClass, and defineHiddenClass for throwaway classes. When you still meet the error on JDK 17 or later, it is usually an old dependency or a plugin, which makes the repair order clear.
- Upgrade first. A library that still reflects into
java.baseinternals has a newer version that does not; opening packages hides the problem for the whole process instead of fixing one dependency. - Then open the single package:
--add-opens java.base/java.lang=ALL-UNNAMEDclears the classic class-definition failure, and it belongs in a comment next to the dependency that needed it. - Executable jars can carry it: the
Add-Opensmanifest attribute holds the same list, so the requirement travels with the artifact instead of living in someone's shell history. - `--add-exports` is the compile-and-link cousin: it covers building against a package that is not exported and does not unlock deep reflection.
Every --add-opens is a permanent hole in the module boundary. Open one package because a named library needs it, write the reason down beside the flag, and remove the flag when the library catches up.
Structure · exports, opens, and the veto
the declaring module decides, the caller only asks
The caller module declaration cannot open anything on the other side; it can only read what it was given.
The historic graveyard: sun.misc.Unsafe
Before modules, the escape hatch of choice was sun.misc.Unsafe, a class that let library code allocate, read and write memory outside the ordinary rules. It worked, it was never supported, and its exit has been scheduled: the memory-access methods were deprecated for removal in JDK 23 (JEP 471) and warn on first use since JDK 24 (JEP 498), with exception-throwing and removal planned for later releases. The Foreign Function and Memory Overview lesson takes the replacement story further; the reflection-facing point is that reaching into internals has an expiry date.
The class also has a history of individual removals once supported replacements existed. Unsafe::defineClass went away in JDK 11 after MethodHandles.Lookup::defineClass; Unsafe::defineAnonymousClass was removed in JDK 17 after Lookup::defineHiddenClass arrived in JDK 15. The frameworks that depended on them moved, which is what keeps the lesson useful rather than nostalgic.
Internals are borrowed time. If a design needs deep reflection into code you do not own, that is a dependency to replace, not a flag to keep.
Reflection bypasses access control, so grant it least
The flag is an access-control bypass by design, which is why it deserves the smallest possible footprint. setAccessible turns unreadable state into readable state for whoever holds the object, and in a process that also deserializes untrusted data that combination is exactly what the gadget material in The Serialization Security Problem depends on. Compile-time visibility, which packages and modifiers express, is the Packages and Access Control lesson's territory; this lesson is the runtime side of the same line, where the enforcement can be switched off if the holder decides to.
- Prefer the public API. A private member is a promise that it may change; the flag makes your code a party to that change, silently, in a different file.
- Keep reflection out of untrusted paths. Validate input before you reflect, and never let a request choose which member gets looked up.
- The old backstop is gone. The SecurityManager was deprecated for removal in JDK 17 (JEP 411) and permanently disabled, with enabling it now an error, in JDK 24 (JEP 486). Nothing will refuse a privileged reflective call on your behalf; the module boundary and your own code are the control.
Treat the flag as a permission you grant yourself. Grant it per member, keep it in one place, comment why it is there, and the design stays honest about where the boundary was bent.
The --add-opens habit
Just add --add-opens is how a temporary workaround becomes architecture: one flag per mysterious failure, nobody remembering which library wanted which package, and a process where every JDK internal is open to everything on the class path. Each flag is a permanent hole in the boundary the platform spent two releases building. Try the upgrade first, name the dependency in a comment, and write down when the flag goes away.
Interview angles
What does setAccessible(true) actually change?+
It clears the Java language access check on that one reflected object, so private fields, methods and constructors become usable through it. It is per object, not per member or class, and it is separate from the module question of whether the flag may be set at all.
The conditions live in the setAccessible javadoc: access can be enabled when the caller is in the same module as the declaring class, or the member is public in a package exported to the caller, or the package is opened to the caller's module. Every package of the unnamed module is open to all modules, which is why class-path code rarely notices any of this.
What changed in JDK 16 and JDK 17?+
JDK 16 (JEP 396) made deep reflection into JDK internals denied by default. JDK 17 (JEP 403) removed the --illegal-access escape hatch, leaving per-package --add-opens and --add-exports as the only keys.
Common misconception: That the change broke setAccessible itself. The API is unchanged; what changed is the module system's default answer, and only for the JDK's own internals.
Can you write a final field with reflection?+
Only a non-static final field of an ordinary class, and only after setAccessible succeeded. Static final fields, fields of hidden classes and fields of records are non-modifiable: Field.set throws IllegalAccessException even with the flag, which on those fields only unlocks reads.
The javadoc is explicit that setting a final field this way is meaningful only during deserialization or reconstruction, and that other uses may have unpredictable effects, including code that keeps using the original value.
Follow-up: What happens to the guarantee for threads that already read that field, a question Final-Field Semantics takes up in full?
Why does a JDK 17 upgrade break old libraries with InaccessibleObjectException?+
Those libraries call setAccessible on JDK internals that are no longer open, such as members of java.lang they wanted to patch or inspect. Newer versions of the same libraries stopped doing that, so upgrade first and reach for --add-opens for the exact package second.
The message names both sides: the member it will not open, and the module that refuses. That second half is the actionable part, and it is also what tells you whether an upgrade or a flag is the honest repair.