如何使用Java中的反射访问超类的超类的私有字段?

And*_*a T 2 java reflection

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

Class A
    - privateField
Class B extends A
Class C extends B
    + method use A.privateField
Run Code Online (Sandbox Code Playgroud)

Duk*_*ing 5

您需要这样做的事实表明设计有缺陷.

但是,可以按如下方式完成:

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));
   }
}
Run Code Online (Sandbox Code Playgroud)

致电:

new C().m();
Run Code Online (Sandbox Code Playgroud)

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));
}
Run Code Online (Sandbox Code Playgroud)