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