Accessing Private Methods in Java

February 18, 2008 – 12:16 am

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

Post a Comment

CAPTCHA image