Sunday 22 April 2012

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

2 comments:

  1. is it Access in constructor ?
    suppose if i create one constructor and i want to access private method in that so is it work ?

    ReplyDelete