Using the Java Reflection API we can indirectly invoke private methods from outside the scope of the class they belong to. The AcceesibleObject class is the base class for Method, Field and Constructor. The AccessibleObject class provides the ability to flag a reflected object and suppress default Java language access control checks. Calling the setAccessible method that was defined in the AccessibleObject class passing over the false boolean value we can indirectly invoke a private method from outside the scope of its class. The following code sample shows that.
import java.lang.reflect.Method;
public class Dmo
{
public static void main(String[] args) throws Exception
{
Person per = new Person();
//per.setName(“david”);
Method meth = Person.class.getDeclaredMethod(“setName”,String.class);
meth.setAccessible(true);
meth.invoke(per, “david”);
System.out.println(per);
}
}
class Person
{
private String name;
private void setName(String str)
{
name = str;
}
public String toString()
{
return name;
}
}