您的位置:首页 > 其它

利用反射调用私有方法

2017-02-13 20:01 183 查看
Teacher类中的私有方法:

private void printToString() {
System.out.println(toString());
}


调用代码:

try {
Teacher t = new Teacher();
Method method = Teacher.class.getDeclaredMethod("printToString");
method.setAccessible(true);
method.invoke(t);
} catch (Exception e) {
e.printStackTrace();
}


NOTE:
method.setAccessible(true);
必须写在
method.invoke(t);
之前。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: