6

在我使用的一个 API 中,我有一个具有私有字段A.privateField )的抽象类Class A)。 B类在 API 中扩展了 A 类。我需要用我的实现Class C扩展 Class B ,但我需要 class A 的 privateField 。我应该使用反射:如何访问超超类的私有字段?

Class A
    - privateField
Class B extends A
Class C extends B
    + method use A.privateField
4

1 回答 1

13

您需要这样做的事实表明设计存在缺陷。

但是,可以按如下方式进行:

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));
}
于 2013-09-16T14:46:23.130 回答