利用java反照机制调用类的私有方法

利用java反射机制调用类的私有方法

引用: 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);

}

 

}