vendredi 9 juin 2017

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 Retriever {
    public static void main(String[] args) throws ReflectiveOperationException {
        Field field = Distant.class.getField("requestedField");
        Class<?> declaredBy = // Where did this field came from?
    }
}





Aucun commentaire:

Enregistrer un commentaire