Java Reflection method invoke a private method

Introduction

Like private fields, a private method may be made accessible using setAccessible() method.

The following simple program demonstrates this:


import java.lang.reflect.Method;

class X {//from www.  jav a  2s .  c om
   private void f() {
      System.out.println("f() called");
   }
}

public class Main {
   public static void main(String args[]) throws Exception {
      Method method = X.class.getDeclaredMethod("f");
      method.setAccessible(true);
      method.invoke(new X());
   }
}



PreviousNext

Related