mercredi 8 février 2017

Why does "superclass = superclass.getSuperclass();" not work in a loop?

I have this method, which grabs all declared fields from a class, including all ancestor classes:

public static List<Field> getAllDeclaredFields(Class<?> type) {
    final List<Field> fields = new LinkedList<>();
    Class<?> superclass = type.getSuperclass();

    fields.addAll(Arrays.asList(type.getDeclaredFields()));
    while (superclass != null) {
        fields.addAll(Arrays.asList(superclass.getDeclaredFields()));
        superclass = superclass.getSuperclass();
    }

    return fields;
}

I realize that I can use reflection here, but that's not the point of my question. My question is, why is this line:

superclass = superclass.getSuperclass(); 

.. not setting the variable to its superclass? The variable just continues to reference the original class, even after the assignment.





Aucun commentaire:

Enregistrer un commentaire