Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In one API I am using I have an Abstract Class (Class A) that has a private field (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
like image 938
Andrea T Avatar asked Sep 16 '13 14:09

Andrea T


1 Answers

The fact that you need to do this points to a flawed design.

However, it can be done as follows:

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

Call with:

new C().m();

One way to do the 'walking up the class hierarchy' that Andrzej Doyle was talking about is as follows:

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));
}
like image 128
Bernhard Barker Avatar answered Sep 21 '22 10:09

Bernhard Barker