如何使用反射访问从抽象 class 继承的字段?
How to access field inherited from an abstract class with Reflection?
所以我有一个抽象的 Geo class 表示 3D 几何形状,所以它继承了 Vector positions 和抽象方法等字段,如 update 和 display。
因为我的 Cube class 继承自这个 Geo class,我没有 re-declare 我的字段,我只是在 Cube [=28= 的构造函数中设置它们].当我没有从 Geo 继承并在 Cube class.
中声明字段时,我最初没有得到错误
但是,我注意到当我尝试查看字段是否存在时它会抛出此错误:
java.lang.NoSuchFieldException: boundBox
这是检查字段的反射代码(object 是一个立方体 object):
try {
Field field = object.getClass().getDeclaredField("boundBox");
} catch(Exception e){
e.printStackTrace();
}
再一次,我没有 re-declare "boundBox" 字段,因为我已经在 Geo 摘要 class 中声明了它。这是我的摘要的基本部分 class 和 child class:
abstract class Geo {
public Vector pos;
public BoundingBox boundBox;
abstract void update();
abstract void display();
}
class Cube extends Geo {
public Cube(Vector pos, float dim){
this.pos = pos;
boundBox = new BoundingBox(pos,dim);
}
@Override
void update(){
}
@Override
void display(){
}
}
使用 Class.getField()
而不是 Class.getDeclaredField()
。 getDeclaredField()
仅考虑由调用该方法的对象的类型声明的字段,而 getField()
递归地提升超类型树以寻找匹配项。
如果您不想硬编码 class 并执行 (Geo.class.getDeclaredField("boundBox")
)。您可以使用 object.getClass().getSuperclass().
访问摘要 class
try {
Field field = object.getClass().getSuperclass().getDeclaredField("boundBox");
} catch(Exception e){
e.printStackTrace();
}
所以我有一个抽象的 Geo class 表示 3D 几何形状,所以它继承了 Vector positions 和抽象方法等字段,如 update 和 display。
因为我的 Cube class 继承自这个 Geo class,我没有 re-declare 我的字段,我只是在 Cube [=28= 的构造函数中设置它们].当我没有从 Geo 继承并在 Cube class.
中声明字段时,我最初没有得到错误但是,我注意到当我尝试查看字段是否存在时它会抛出此错误:
java.lang.NoSuchFieldException: boundBox
这是检查字段的反射代码(object 是一个立方体 object):
try {
Field field = object.getClass().getDeclaredField("boundBox");
} catch(Exception e){
e.printStackTrace();
}
再一次,我没有 re-declare "boundBox" 字段,因为我已经在 Geo 摘要 class 中声明了它。这是我的摘要的基本部分 class 和 child class:
abstract class Geo {
public Vector pos;
public BoundingBox boundBox;
abstract void update();
abstract void display();
}
class Cube extends Geo {
public Cube(Vector pos, float dim){
this.pos = pos;
boundBox = new BoundingBox(pos,dim);
}
@Override
void update(){
}
@Override
void display(){
}
}
使用 Class.getField()
而不是 Class.getDeclaredField()
。 getDeclaredField()
仅考虑由调用该方法的对象的类型声明的字段,而 getField()
递归地提升超类型树以寻找匹配项。
如果您不想硬编码 class 并执行 (Geo.class.getDeclaredField("boundBox")
)。您可以使用 object.getClass().getSuperclass().
try {
Field field = object.getClass().getSuperclass().getDeclaredField("boundBox");
} catch(Exception e){
e.printStackTrace();
}