How to access the private methods of a class from outside of the class in Java?


You can access the private methods of a class using java reflection package.

Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.

Step2 − Set the method accessible by passing value true to the setAccessible() method.

Step3 − Finally, invoke the method using the invoke() method.

Example

import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod() {
      System.out.println("hello");
   }
}

public class SampleTest {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("DemoTest");
      Object obj = c.newInstance();
      Method method = c.getDeclaredMethod("sampleMethod", null);
      method.setAccessible(true);
      method.invoke(obj, null);
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements