Course contentsShow
← Java
Lesson 2365 of 2,87045. Reflection APIFree lesson

Security Manager and Module System Restrictions

Understand how SecurityManager and JPMS limit setAccessible, requiring explicit exports or opens declarations.

Security Manager and Module System Restrictions

What you'll learn: How Java's SecurityManager and the Java Platform Module System (JPMS) restrict reflective access, requiring explicit permission to use setAccessible().

The Era of Access Control

While setAccessible(true) lets you bypass Java's normal access controls, both the SecurityManager (legacy) and the module system (modern) can block this power when security policies demand it.

SecurityManager Restrictions (Legacy)

When a SecurityManager is active, calling setAccessible(true) requires the ReflectPermission("suppressAccessChecks") permission. Without it, you'll get a SecurityException:

// If SecurityManager denies permission:
field.setAccessible(true); // throws SecurityException

Think of SecurityManager as a strict guard at the door—it checks your credentials before allowing you to disable access checks.

Module System Restrictions (Modern)

Starting with Java 9+, the Java Platform Module System (JPMS) adds another layer. Even without a SecurityManager, reflective access to non-public members requires the target module to explicitly export (public members) or open (non-public members) its packages.

If a module doesn't declare itself opens or use opens directives in module-info.java, setAccessible(true) will throw an InaccessibleObjectException:

// Accessing private field from a closed module:
field.setAccessible(true); // throws InaccessibleObjectException

You can work around this using JVM flags like --add-opens, but production code should respect module boundaries.

The Security Principle

Both mechanisms enforce strong encapsulation: reflection shouldn't silently break guarantees that modules or security policies establish. If you need reflective access, you must declare it explicitly through module descriptors or security policies.

Key Takeaway:
SecurityManager and JPMS both restrict setAccessible() to enforce encapsulation—SecurityManager via permissions, JPMS via explicit exports or opens declarations in modules.