出于一个应用需要,要访问父类的私有成员,研究了一下,这么实现:
public static Object get(Object instance, String variableName)
{
Class targetClass = instance.getClass().getSuperclass();
// YourSuperClass 替换为实际的父类名字
YourSuperClass superInst = (YourSuperClass)targetClass.cast(instance);
Field field;
try {
field = targetClass.getDeclaredField(variableName);
//修改访问限制
field.setAccessible(true);
// superInst 为 null 可以获取静态成员
// 非 null 访问实例成员
return field.get(superInst);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
把上面的 get() 方法放到子类中,使用也很简单,传入 this 指针,传入成员变量的名字。比如:
get(this, "mPrivateMember");