如何在Java中通过反射访问父类的父类的私有字段? [英] How to access a private field of the super class of the super class with reflection in Java?
问题描述
在一个正在使用的API中,我有一个抽象类( A类),该类具有私有字段( A.privateField ). B类 扩展了API中的A类.我需要扩展B类及其实现,即 C类,但是我需要A类的privateField.我应该使用反射:如何访问超超类的私有字段?
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));
}
}
致电:
new C().m();
Andrzej Doyle所说的遍历类层次结构" 的一种方法如下:
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));
}
这篇关于如何在Java中通过反射访问父类的父类的私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!