jeudi 9 juillet 2020

How can I sort with reflection in Java?

I have my Client table and I have one name, id, updateDate field and oneToMany relationship with user entity.

I want to sort the Client list with reflection. Because my sort field comes as a string. For example, I get strings like "c.id", c.user.name "and I want to sort accordingly.

List clientList = ..

clientList.sort(Comparator.comparing (report -> report.getClass ().getDeclaredField ("updateDate") {
try {
report.getClass ().getDeclaredField ("updateDate").setAccessible (true);
java.lang.reflect.Field a = report.getClass().getDeclaredField ("updateDate");
a.setaccessible (true);

return (Comparable) a.get(report);
}
  catch (Exception e) {
throw new RuntimeException ("Ooops", e);
}

But when I get null here, I get an error and I can sort with user.name. Can you help me ?





Aucun commentaire:

Enregistrer un commentaire