如果我有一个等级类:
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(); }
}
现在,如果我有一个Class<Distant>
,那么从requestField
类中获取已声明Distant
的类对象的正确方法是什么?
class Retriever {
public static void main(String[] args) throws ReflectiveOperationException {
Field field = Distant.class.getField("requestedField");
Class<?> declaredBy = // Where did this field came from?
}
}
答案 0 :(得分:1)
调用getDeclaringClass()
类的Field
方法,找到定义字段的类。