title: Invoking methods in Comparator comparing method
body: <p>I have an ArrayList&lt;<strong>Task</strong>> named <strong>tasks</strong> which I want to print, sorted according to each field of the <strong>Task</strong> object.
  Task class has three private fields { String <strong>title</strong>, Date <strong>date</strong>, String <strong>project</strong> }.
  The class has some public get methods that allow other classes to read the fields { <strong>getTitle()</strong>, <strong>getDate()</strong>, <strong>getProject()</strong>, <strong>getTaskDetails()</strong> }.</p>
  
  <p>I have a simple method that uses a stream to sort and print the ArryaList tasks:</p>
  
  <pre><code>tasks.stream()
       .sorted(Comparator.comparing(Task::getProject))
       .map(Task::getTaskDetails)
       .forEach(System.out::println);
  </code></pre>
  
  <p>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 ( <strong>getTitle()</strong>, <strong>getDate()</strong>, <strong>getProject()</strong> ) inside the Comparator comparing method:</p>
  
  <p>Used <code>import java.lang.reflect.Method;</code></p>
  
  <p>Declared the method <code>Method taskMethod = Task.class.getDeclaredMethod(methodName);</code> where <strong>methodName</strong> will be the parameter String received with the method name (<strong>"getTitle"</strong> or <strong>"getDate"</strong> or <strong>"getProject"</strong>).</p>
  
  <p>Then tried to do something like this, but didn't workout:</p>
  
  <pre><code>            tasks.stream()
                      .sorted(Comparator.comparing(task -&gt; {
                                  try {
                                      taskMethod.invoke(task);
                                  } catch (Exception e) {
                                      e.printStackTrace();
                                  }
                              }))
                      .map(Task::getTaskDetails)
                      .forEach(System.out::println);
  </code></pre>
  
  <p>Is this possible at all? Or is there any simpler solution?</p>
  
  <p>Only found this <a href="https://stackoverflow.com/questions/39463175/how-can-we-pass-a-variable-field-method-name-in-comparator-comparing">question</a> but didn't solve my problem.</p>
  
  <p>Thank you for any feedback.</p>