读书人

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

发布时间: 2012-12-22 12:05:05 作者: rapoo

利用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);

}

?

}


读书人网 >编程

热点推荐