在一个API中,我使用的是一个具有私有字段(A.privateField)的抽象类(Class A)。
B类在API中扩展了A类。
我需要用我的实现C类扩展B类,但是我需要A类的privateField。
我应该使用反射:如何访问超超类的私有字段?
Class A
- privateField
Class B extends A
Class C extends B
+ method use A.privateField
最佳答案
您需要执行此操作的事实表明设计存在缺陷。
但是,可以按照以下步骤进行:
class A
{
private int privateField = 3;
}
class B extends A
{}
class C extends B
{
void m() throws NoSuchFieldException, IllegalAccessException
{
Field f = getClass().getSuperclass().getSuperclass().getDeclaredField("privateField");
f.setAccessible(true); // enables access to private variables
System.out.println(f.get(this));
}
}
致电:
new C().m();
Andrzej Doyle所说的“提高类层次结构”的一种方法如下:
Class c = getClass();
Field f = null;
while (f == null && c != null) // stop when we got field or reached top of class hierarchy
{
try
{
f = c.getDeclaredField("privateField");
}
catch (NoSuchFieldException e)
{
// only get super-class when we couldn't find field
c = c.getSuperclass();
}
}
if (f == null) // walked to the top of class hierarchy without finding field
{
System.out.println("No such field found!");
}
else
{
f.setAccessible(true);
System.out.println(f.get(this));
}