setAccessible and opens: How They Interact
What you'll learn: How setAccessible(true) behaves within the module system and why it depends on proper opens declarations.
The Reflection Permission Bridge
Before JPMS, calling setAccessible(true) on a Field, Method, or Constructor object would bypass Java's access controls, letting you reach private members. The module system adds a new layer: even setAccessible(true) cannot breach module boundaries unless the package is explicitly opened.
Think of it this way: setAccessible is like having a lockpick, but modules add a locked gate in front of the door. The opens directive is the key to that gate.
How It Works
When you call setAccessible(true) on a reflective object:
- Within the same module: Works as before—you can access private members
- Across module boundaries without
opens: ThrowsInaccessibleObjectException, even if you've calledsetAccessible(true) - Across module boundaries with
opens:setAccessible(true)succeeds, granting deep reflection access
This means frameworks like Spring or Hibernate that rely on reflection must have the packages they inspect opened to them—either unconditionally (opens com.example.entities;) or with qualified opens (opens com.example.entities to spring.core;).
The Exception You'll Encounter
If a package isn't opened and you attempt reflection:
// Assuming module doesn't open the package
Field field = SomeClass.class.getDeclaredField("privateField");
field.setAccessible(true); // Throws InaccessibleObjectException
The error message will clearly state which module needs to open which package.
Key Takeaway:
setAccessible(true) only bypasses Java access modifiers (private, protected) but cannot cross module boundaries unless the target package is explicitly opens to your module—the module system's strong encapsulation trumps traditional reflection unless you grant permission.