【无标题】

‘’’
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);
}

}

‘’’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值