如何在 Java 7 中对 .class 文件中的属性实现自定义排序

use*_*982 3 java sorting

我需要根据Student对象的name. 请注意,没有实现compareTo()Student类,简单的getter和setter方法只和阶级本身的一部分,school.jar这是我用我的教育门户项目。如何访问这些字段,我可以引入相同的基类,但标记为final.

这个用例在技术上是否可行?如果是这样,我如何实现它?

Mur*_*nik 6

您不需要修改Student类 - 您可以引入自己的类Comparator

public class StudentNameComparator implements Comparator<Student> {
    @Override
    int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2.getName());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

Collections.sort(listOfStudents, new StudentNameComparator());
Run Code Online (Sandbox Code Playgroud)

编辑:
强制性评论:Java 8(或更高版本)将允许对此进行一些语法糖(例如Comparator.comparing(Student::getName)),但要求是使用 Java 7。