Article: Accessing Private Methods in Java
In every introductory Java programming class (and probably every tutorial or book), students are taught that
private fields and methods can only be accessed by methods of the same class. Though this would seem to be a
security control, using private visibility can be easily overridden, as shown below:
import java.lang.reflect.*;
class A {
private void f() {
System.out.println("Running A.f()");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Class a = new A().getClass();
Method m = a.getDeclaredMethod("f", null);
m.setAccessible(true);
m.invoke(new A(), null);
}
}
Scovetta.com is a personal website. Opinions expressed are my own, and not those of my employer or any groups I am affiliated with.
|