title: Sort a List of Objects based on runtime property
body: <p>I have a <code>List</code> of <a href="https://stackoverflow.com/questions/1612334/difference-between-dto-vo-pojo-javabeans">Value Objects</a> [VO]. These Objects have many properties and corresponding get/set methods. I want to sort this <code>List</code> based on a property which I'll be getting in runtime.
  Let me explain in detail...</p>
  
  <p>My VO is like this:</p>
  
  <pre><code>public class Employee {
      String name;
      String id;
  
      private String getName() {
          return name;
      }
  
      private String getId() {
          return id;
      }
  }
  </code></pre>
  
  <p>I will be getting a string <code>sortType</code> in runtime, which can be either <code>"id"</code> or <code>"name"</code>. I want to sort the list based on the value of the <code>String</code>.</p>
  
  <p>I have tried to use <code>Comparator</code> and reflection together, but no luck. May be I didn't use it properly. I don’t want to use conditional <code>if</code> block branching to create whichever new specific <code>Comparator</code> [anonymous inner Class] is needed (at the runtime). Any other thoughts?   </p>
  
  <hr>
  
  <p>The try catch should be inside the new class. Here is the working code. If you want to use a separate class for <code>Comparator</code>, please find it in @Bohemian's comment below.</p>
  
  <pre><code>        String sortType = "name"; // determined at runtime
          Collections.sort(results, new Comparator&lt;Employee&gt;() {
          public int compare(Employee c1, Employee c2) {
              try{
              Method m = c1.getClass().getMethod("get" + StringUtils.capitalize(sortType));
              String s1 = (String)m.invoke(c1);
              String s2 = (String)m.invoke(c2);
              return s1.compareTo(s2);
              }
              catch (Exception e) {
                  return 0;
              }
          }
         });
  </code></pre>