Can private methods of a class be accessed from outside of a class in Java?

Java 8Object Oriented ProgrammingProgramming

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);
   }
}
raja
Published on 02-Jan-2018 06:44:05
Advertisements