//PrivateMethod.java
class PrivateMethod
{
private void printMessage()
{
System.out.println("hello rakesh:");
}
}
//AccessPrivate.java
import java.lang.reflect.*;
class AccessPrivate
{
public static void main(String args[]) throws Exception
{
Class c=Class.forName("PrivateMethod");
Object o=c.newInstance();
Method m=c.getDeclaredMethod("printMessage",null);
m.setAccessible(true);
m.invoke(o,null);
}
}
试试这个代码(我在cmd的jdk 1.7上测试了它):
Class<?> c=Class.forName("PrivateMethod");
Object o=c.newInstance();
Method m=c.getDeclaredMethod("printMessage");
m.setAccessible(true);
m.invoke(o);