Issue
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;
}
Note, the class Apple is a regular POJO with private fields and public getters/setters.
Solution
Something like this. It will throw a ClassCastException if the field can't be compared.
Bit ugly, but isn't reflection always.
<T extends Comparable<T>> List<Apple> sortApplesByFieldName(List<Apple> apples, String fieldName)
throws NoSuchFieldException {
Field field = Apple.class.getDeclaredField(fieldName);
return apples.stream()
.sorted(Comparator.comparing(apple -> {
try {
return (T) field.get(apple);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}))
.collect(Collectors.toList());
}
Answered By - Michael
Answer Checked By - Cary Denson (JavaFixing Admin)