Tuesday, October 2, 2012

Can we access private methods in other class?..yes we can using reflection api


Yes...We can access private methods in other class using reflection API

Example code:

MyClass.java with private method
public class MyClass {

private String myPrivateMethod(String name) {
//Do something private
return "Hello "+;
}
}

Test class:  MainTest.java public class MainTest class{

private MyClass underTest;


public static void main(String []args)throws Exception {

MyClass underTest= new MyClass();

Class[] parameterTypes = new Class[1];
parameterTypes[0] = java.lang.String.class;

Method m = underTest.getClass().getDeclaredMethod("myPrivateMethod", parameterTypes);
m.setAccessible(true);

Object[] parameters = new Object[1];
parameters[0] = "Shekhar Reddy!";

String result = (String) m.invoke(underTest, parameters);
System.out.println(result )//Shekhar Reddy!

}


}
outPut: Hello Shekhar Reddy!

No comments: