Java中的Java通用方法调用

Meh*_*hdi 1 java java-ee

想象一下,我有两个POJO bean:

public class Employee {
   private String name;
   private long id;
   ....
   //GETTERS AND SETTERS
}

public class Buildings {
   private String name;
   private long numOfEmployees;
   ...
   //GETTERS AND SETTERS
}   
Run Code Online (Sandbox Code Playgroud)

现在我制作了两个POJO列表(empList和bldList),我想使用Collections.sort这样对它们进行排序:

Collections.sort(empList , new Comparator<Employee>() {
       public int compare(Employee o1, Employee o2) {
         return o2.getId().compareTo(o1.getId());
       }
});
Run Code Online (Sandbox Code Playgroud)

和另一个这样的排序:

Collections.sort(bldList, new Comparator<Buildings>() {
       public int compare(Buildings o1, Buildings o2) {
         return o2.getNumOfEmployees().compareTo(o1.getNumOfEmployees());
       }
});
Run Code Online (Sandbox Code Playgroud)

现在我没有为此编写比较器两次,而是认为我找到了一个解决方案,我可以使用泛型并在方法中执行此操作,我想到的是一个类似于此的方法:

public <T> List<T> sortMyList(List<T> list){
   Collections.sort(list, new Comparator<T>() {
         public int compare(T o1, T o2) {
            // I don't know how to call the Building and Employee methods here so I just show it with "???"
            return o1.???.compareTo(o2.???);
          }
   });
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让这种方法适合我?

Nar*_*hai 5

让你的类实现Comparable<T>.

class Employee implements Comparable<Employee>{

   //override compareTo()

}
Run Code Online (Sandbox Code Playgroud)

同样的 Buildings

然后用 Collections.sort(listOfEmployee);