Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java trySetAccessible: handle a denied deep-reflection request

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

AccessibleObject.trySetAccessible attempts to suppress language access checks and returns false when access cannot be enabled under module boundaries.

Operational contract

The sample reflects a fixed private auditCode method on an application-owned object. It refuses to invoke when the declaring module does not allow deep reflection to the caller. This operation is appropriate only for a deliberate integration contract; public APIs are preferable. An exported package does not necessarily permit access to private members. If the target belongs to another named module, its package normally needs an opens directive to the caller's module. A failed request must not be worked around by silently depending on runtime flags.

Failure case

A plugin updates to a named module and stops opening its internal package. The check rejects the integration clearly rather than assuming setAccessible can override the module boundary.

Java code

Java
import java.lang.reflect.Method;
import java.util.Objects;

public class AuditCodeAccess {
    public static String read(Object auditRecord) throws ReflectiveOperationException {
        Objects.requireNonNull(auditRecord);
        Method method = auditRecord.getClass().getDeclaredMethod("auditCode");
        if (!method.canAccess(auditRecord) && !method.trySetAccessible())
            throw new IllegalStateException("Audit package is not open to this module");
        return (String) method.invoke(auditRecord);
    }
}

Performance and ownership cost

Method lookup, access check, and invocation add O(1) application space with reflective overhead. Reflection does not make module encapsulation free; configuration and compatibility testing are part of this integration cost.

Common Mistakes

  • Do not assume exports also opens private members.
  • Do not ignore a false trySetAccessible result.
  • Do not call deep reflection on arbitrary classes supplied by untrusted input.

Connected lessons

java
module boundaries
reflection-trysetaccessible-module
Storage details