Java Comparator given the name of the property to compare

烂漫一生 提交于 2019-12-01 07:15:43

Bean Comparator should work.

What you could do is make the comparator take a String representing the name of the parameter to sort by in its constructor.

Then you could use reflection to sort by the given parameter.

The following code is very dirty. But I think it illustrates the gist of what you would need to do.

public class FieldComparator<T> implements Comparator<T> {
    String fieldName;

    public FieldComparator(String fieldName){
        this.fieldName = fieldName;
    }

    @Override
    public int compare(T o1, T o2) {
        Field toCompare = o1.getClass().getField(fieldName);
        Object v1 = toCompare.get(o1);
        Object v2 = toCompare.get(o2);
        if (v1 instanceof Comparable<?> && v2 instanceof Comparable<?>){
            Comparable c1 = (Comparable)v1;
            Comparable c2 = (Comparable)v2;
            return c1.compareTo(c2);
        }else{
            throw new Exception("Counld not compare by field");
        }
    }
}

Yes, you could use the reflection API, to get the content of a field based on it's name.

See Field class and especially the Field.get method.

(I wouldn't recommend it though, as reflection is not designed for this type of task.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!