Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, how do I sort a generic class T on a Field variable sent to me

// this function can be called if the objects sent is Comparable (they have
// already chosen the field and how it compares)
public void mySort(Object [] obj) {
     Arrays.sort(obj, null);     // this sorts based on compareTo() 
                                 // method of comparable object
}

My question is how would the following function need to be changed to sort the array by the Field field. I have tried many different ways of implementing it and just put code below which represents what I was trying to do.

// this function should be used to sort a generic array of T objects, to be
// compared on the Field field
public static <T> void mySort2(T [] obj, Field field) {
    Collections.sort(obj, new Comparator<T>(){
          public int compare(T obj1, T obj2)
          {
             return obj1.field.compareTo(obj2.field); // this does not work
                             //  since I need to the name of the field and
                             //  not a variable, however I do not know what
                             //  T will be when it is sent to me
          }
      });
}
like image 392
Mike N Avatar asked Dec 08 '22 01:12

Mike N


1 Answers

You need to use Field::get to reflectively access the field. After that, you will need to cast to Comparable.

like image 60
Jeffrey Avatar answered Dec 11 '22 09:12

Jeffrey