Access the Private method from outside class in Java

You can access private method from outside class by changing the runtime behavior of the class

public method getDeclareMethod(String name,Class[] parameterTypes) throws NoSuchMethodException,SecurityException : returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

 


public class DynamicClass {
 
    private void show(){
     System.out.println("Test");
    }
}

import java.lang.reflect.Method;
 
public class AccessPrivateMethod {
 
    public static void main(String args[]){
        try{
            Class clsClass = Class.forName("DynamicClass");
            Object o = clsClass.newInstance();
            Method method = clsClass.getDeclaredMethod("show", null);
            method.setAccessible(true);
            method.invoke(o, null);
        }catch(Exception e){
         e.printStackTrace();
        }
 
    }
}


Result : Test