We can use Reflection to access private method of a class from
outside the class. IN Java, we use getDeclaredMethod() to get
instance of a private method. Then we mark this method accessible
and finally invoke it.
In following sample code, we are accessing private method
message() of class Foo by Reflection.
FileName: Foo.java
public class Foo {
private void message(){System.out.println("hello java"); }
}
FileName: FooMethodCall.java
import java.lang.reflect.Method;
public class FooMethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName("Foo");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true);
m.invoke(o, null);
}
}