在java中,如何在发送给我的Field变量上对泛型类T进行排序

Mik*_*e N 4 java sorting generics field

// 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
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何通过Field字段更改以下函数来对数组进行排序.我已经尝试了许多不同的方法来实现它,只需将代码放在下面,代表我想要做的事情.

// 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
          }
      });
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*rey 9

您需要使用Field::get反射访问该字段.在那之后,你需要施展Comparable.