簡體   English   中英

如何通過Java中的反射訪問超級class的超級class的私有字段?

[英]How to access a private field of the super class of the super class with reflection in Java?

在我使用的一個 API 中,我有一個摘要 Class ( Class A ),它有一個私有字段( A.privateField )。 Class B extends Class A within the API. I need to extend Class B with my implementation of it, Class C , but I need privateField of class A. I should use reflection: How can I access a private field of a super super class?

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));
}

另一種方法,如果您使用的是 springframework。

// Attempt to find a field on the supplied Class with the supplied name. Searches all superclasses up to Object.
Field field = ReflectionUtils.findField(C.class, "privateField");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM