mercredi 9 octobre 2019

Invoking methods in Comparator comparing method

I have an ArrayList<Task> named tasks which I want to print, sorted according to each field of the Task object. Task class has three private fields { String title, Date date, String project }. The class has some public get methods that allow other classes to read the fields { getTitle(), getDate(), getProject(), getTaskDetails() }.

I have a simple method that uses a stream to sort and print the ArryaList tasks:

tasks.stream()
     .sorted(Comparator.comparing(Task::getProject))
     .map(Task::getTaskDetails)
     .forEach(System.out::println);

Instead of creating 3 different methods, to sort according each different getter method, I wanted to use Reflection API. But I am having trouble invoking the methods ( getTitle(), getDate(), getProject() ) inside the Comparator comparing method:

Used import java.lang.reflect.Method;

Declared the method Method taskMethod = Task.class.getDeclaredMethod(methodName); where methodName will be the parameter String received with the method name ("getTitle" or "getDate" or "getProject").

Then tried to do something like this, but didn't workout:

            tasks.stream()
                    .sorted(Comparator.comparing(task -> {
                                try {
                                    taskMethod.invoke(task);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }))
                    .map(Task::getTaskDetails)
                    .forEach(System.out::println);

Is this possible at all? Or is there any simpler solution?

Only found this question but didn't solve my problem.

Thank you for any feedback.





Aucun commentaire:

Enregistrer un commentaire