dimanche 28 août 2022

How to sort a collection based on java.lang.reflect.Field? [duplicate]

I'm stuck in a situation where I only got Fields (java.lang.reflect) of a given class.

To help you better imagine, let's say we have code:

List<Apple> sortApplesByFieldName(List<Apple> apples, String fieldName) {
    Field field = Apple.class.getDeclaredField(fieldName);

    // some stream logic for sorting using this var
    return apples;
}

Can someone actually solve this problem?

Also, using a switch statement is not an option, as fields can change.

Note, the class Apple is a regular POJO with private fields and public getters/setters.





Aucun commentaire:

Enregistrer un commentaire