Invoking Private Methods with setAccessible
What you'll learn: How to use Method.setAccessible(true) to invoke private methods reflectively, bypassing Java's normal access restrictions.
The Core Idea
Just as you used setAccessible to break into private fields, you can apply the same technique to private methods. Normally, calling Method.invoke() on a private method triggers an IllegalAccessException. By calling setAccessible(true) on the Method object first, you override Java's access control and force the method to become accessible—even though it was designed to be internal.
This is like having a master key that opens doors marked "Staff Only." The door was locked for a reason, but sometimes testing frameworks or specialized libraries need to peek inside.
How It Works
- Obtain the Method object using
getDeclaredMethod()(which can see private methods) - Call
setAccessible(true)on the Method object - Invoke it normally with
invoke()
class SecretService {
private String classify(String data) {
return "CLASSIFIED: " + data;
}
}
// Breaking in reflectively
SecretService service = new SecretService();
Method method = SecretService.class.getDeclaredMethod("classify", String.class);
method.setAccessible(true); // Disable access control
String result = (String) method.invoke(service, "Top Secret");
// result is now "CLASSIFIED: Top Secret"
When and Why
You're deliberately violating the intended API boundaries. This is primarily useful for:
- Testing private logic without exposing it publicly
- Framework magic (dependency injection, mocking libraries)
- Debugging or introspection tools
Key Takeaway: Method.setAccessible(true) lets you invoke private methods reflectively, breaking encapsulation just like with private fields—powerful for testing and frameworks, but risky for production code.