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

IllegalAccessException and Access Control

Understanding when IllegalAccessException is thrown and how method accessibility affects invocation.

IllegalAccessException and Access Control

You'll learn when reflection throws IllegalAccessException and how method visibility impacts reflective invocation.

What Is IllegalAccessException?

When you use Method.invoke() to call a method reflectively, Java enforces the same access control rules as normal method calls—most of the time. An IllegalAccessException is thrown when you attempt to invoke a method (or access a field or constructor) that your code doesn't have permission to access.

The Access Control Problem

Think of it like trying to open a locked office door: even though you know the door exists and where it is, you can't just walk in without proper clearance. Similarly, even though reflection lets you obtain a Method object representing a private method, that doesn't automatically grant you permission to invoke it.

class Secret {
    private void hideaway() {
        System.out.println("This is private!");
    }
}

// Later, attempting reflective invocation:
Method m = Secret.class.getDeclaredMethod("hideaway");
m.invoke(new Secret()); // IllegalAccessException thrown!

The exception occurs because hideaway() is private and we haven't bypassed the access check.

Bypassing Access Control with setAccessible

Java provides setAccessible(true) to suppress access checks for reflection. This is the "master key" that lets you invoke private, protected, or package-private members:

Method m = Secret.class.getDeclaredMethod("hideaway");
m.setAccessible(true); // Bypass access control
m.invoke(new Secret()); // Now works: prints "This is private!"

Use this power responsibly—it breaks encapsulation and is typically reserved for frameworks, testing tools, and serialization libraries.

Key Takeaway:
IllegalAccessException is thrown when reflective access violates Java's visibility rules; use setAccessible(true) to bypass access checks, but only when necessary and appropriate.