[英]How do I discover which class has declared a field?
If I have an hierarchical class: 如果我有一个等级课程:
class Root {
private String requestedField; // This is private, so Class<Root> is not the owner!
}
class RealOwner extends Root {
public String requestedField; // This is visible from Class<Distant>
RealOwner() { super(); }
}
class Middle extends RealOwner {
Middle() { super(); }
}
class Distant extends Middle {
Distant() { super(); }
}
Now I if I have a Class<Distant>
, what is the proper way to get the class object which has declared the requestField
that is visible from the Distant
class? 现在,如果我有Class<Distant>
,那么获取声明了从Distant
类可见的requestField
的类对象的正确方法是什么?
class Retriever {
public static void main(String[] args) throws ReflectiveOperationException {
Field field = Distant.class.getField("requestedField");
Class<?> declaredBy = // Where did this field came from?
}
}
调用Field
类的getDeclaringClass()
方法以查找定义Field
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.