In [41]:
import java.lang.reflect.Method;
class Check {
private void privateMethod() {
System.out.println("A private method is called from outside");
}
private void privateMethodWithParam(String fname, long n) {
System.out.println("Hello " + fname + " " + n + ", a private Method is called from outside.");
}
public void printData() {
System.out.println("Public Method");
}
}
Out[41]:
Invoke a private method without parameters.
In [42]:
import java.lang.reflect.Method;
Check check = new Check();
// get the private method
Method method = Check.class.getDeclaredMethod("privateMethod");
// make it accessible
method.setAccessible(true);
// invoke the method
method.invoke(check);
Out[42]:
Invoke a private method with parameters.
In [45]:
import java.lang.reflect.Method;
Check check = new Check();
// get the private method
Method method = Check.class.getDeclaredMethod("privateMethodWithParam", String.class, long.class);
// make it accessible
method.setAccessible(true);
// invoke the method
method.invoke(check, "Ben", 2);
Out[45]:
In [ ]: