Can private methods of a class be accessed from outside of a 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.


import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod() {

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.invoke(obj, null);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 18-Feb-2020

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started