‘’’
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DynamicSortExample {
static class Person {
private String name;
private int age;
// 构造函数、getter和setter省略
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 假设getter方法已定义
public String getName() { return name; }
public int getAge() { return age; }
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static <T> Comparator<T> createComparator(Class<T> clazz, String fieldName) {
try {
// 获取字段
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true); // 确保私有字段也可访问
// 根据字段类型创建Comparator
Class<?> fieldType = field.getType();
if (fieldType == String.class) {
return (o1, o2) -> {
String v1 = (String) field.get(o1);
String v2 = (String) field.get(o2);
return v1.compareTo(v2);
};
} else if (fieldType == Integer.TYPE || fieldType == Integer.class) {
return (o1, o2) -> {
int v1 = field.getInt(o1);
int v2 = field.getInt(o2);
return Integer.compare(v1, v2);
};
}
// 可以为其他类型添加更多的else if
// 如果字段类型不支持比较,则抛出异常
throw new IllegalArgumentException("Unsupported field type for sorting: " + fieldType);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 按名字排序
Collections.sort(people, createComparator(Person.class, "name"));
System.out.println("Sorted by name: " + people);
// 按年龄排序
Collections.sort(people, createComparator(Person.class, "age"));
System.out.println("Sorted by age: " + people);
}
}
‘’’