引用: http://blog.chinaunix.net/uid-26884465-id-3337802.html
测试后,确实可以调用类中的私有方法,前提是知道该私有方法的声明。测试代码如下:
class One {
One(){}
private void testMethod(){
System.out.println("invoked");
}
}
public class LittleTest {
@Test
public void test() throws Exception {
One one = new One();
Class cls= one.getClass();
Method method = cls.getDeclaredMethod("testMethod", null);
method.setAccessible(true);
method.invoke(one, null);
}
}
本文展示了如何在Java中通过反射API调用类的私有方法,并提供了测试代码示例。
195

被折叠的 条评论
为什么被折叠?



