在开发过程中,经常会碰到一种场景就是子类想调用父类的某个私有方法,可采用反射形式实现:
Class cls=.....;//该类为父类的class
Method mt=null;
try {
//先获取方法
mt=cls.getDeclaredMethod(method, new Class[]{.....});
//把方法的访问属性设置为true
mt.setAccessible(true);
mt.invoke(ui, new Object[]{});
} catch (Exception e1) {
e1.printStackTrace();
}
本文介绍了一种在开发过程中,子类通过反射机制调用父类私有方法的方法。具体步骤包括:获取父类的Class对象,使用getDeclaredMethod获取私有方法,并通过setAccessible将访问权限设为true,最后利用invoke方法执行私有方法。
2814

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



