'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
Solution 1:[1]
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));
}
Solution 2:[2]
An alternative way, if you're using 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");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | masonshu |