Accessing Private Methods in Java

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);
  }
}

The simple lesson is that private methods don’t carry any security guarantees.