Accessing Private method outside the class using reflection
Consider a situation where we need to test the private method of class. We cannot directly access this by creating object of the class.
Only way to access the private methods and variables from outside the class using reflection.
Lets see this with the below example.
We can create a class called privateTest which has a private method called display.
1 2 3 4 5 6 7 |
public class PrivateTest { private void display() { System.out.println("This is from display method"); } } |
Now lets see how can we access the private method from outside by using reflection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Test { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { PrivateTest privateTest= new PrivateTest(); Method privateMethod = PrivateTest.class.getDeclaredMethod("display"); privateMethod.setAccessible(true); privateMethod.invoke(privateTest); } } |
output
This is from display method
By default reflection will not allow accessing private methods , To make it happen we have to use the method setAccessible with value as true;
The below method in the mentioned example.
privateMethod.setAccessible(true);
Asif says
August 1, 2012 at 10:50 amAwesome!!!!!!!!!!!!!! article…
Arbuda says
August 1, 2012 at 12:06 pmCan u please post the example to access the parametrized private methods through reflection
admin says
August 1, 2012 at 1:17 pmpublic class PrivateTest {
private void display(String name)
{
System.out.println(“You have passed the parameter : “+name);
}
}
————————————————————————————
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException {
PrivateTest privateTest = new PrivateTest();
Class[] arg1 = { String.class };
Method privateMethod = PrivateTest.class.getDeclaredMethod(“display”,
arg1);
privateMethod.setAccessible(true);
privateMethod.invoke(privateTest, “j2eereference.com”);
}
}
Output
You have passed the parameter : j2eereference.com
bs.mohankumar@gmail.com says
August 1, 2012 at 1:20 pmVery nice man .:)