如何发现哪个类声明了字段?

时间:2017-06-10 03:20:44

标签: java reflection

如果我有一个等级类:

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?
    }
}

1 个答案:

答案 0 :(得分:1)

调用getDeclaringClass()类的Field方法,找到定义字段的类。