I have a Dummy
class that has a private method called sayHello
. I want to call sayHello
from outside Dummy
. I think it sh
Example of accessing private method(with parameter) using java reflection as follows :
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Test
{
private void call(int n) //private method
{
System.out.println("in call() n: "+ n);
}
}
public class Sample
{
public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
{
Class c=Class.forName("Test"); //specify class name in quotes
Object obj=c.newInstance();
//----Accessing private Method
Method m=c.getDeclaredMethod("call",new Class[]{int.class}); //getting method with parameters
m.setAccessible(true);
m.invoke(obj,7);
}
}