Тот факт, что вам нужно это сделать, указывает на ошибочный дизайн.
Однако, это может быть сделано следующим образом:
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();
Один способ сделать «идущий вверх по иерархии классов» Анджей 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));
}
Я думаю, что частное поле класса A может быть p вместо частного, вместо того, чтобы использовать его, вы можете получить доступ к нему из класса C без отражения. – conca