我们如何在Comparator.comparing中传递变量字段/方法名称 [英] How can we pass a variable field /method name in Comparator.comparing

查看:611
本文介绍了我们如何在Comparator.comparing中传递变量字段/方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Report {String name, Date date, int score }类. 我希望能够使用新的Java 8语法对任何成员变量的报告列表进行排序

I have a Report {String name, Date date, int score } class. I want to be able to sort a list of reports for any member variable using the new java 8 syntax

所以Java 8提供了这个新的

So java 8 provides this new

list.sort(Comparator.comparing(report -> report.name)) 

按名称对列表进行排序.

to sort the list on name.

让我们说说我想为该方法提供一个可变字段名称,而不是名称.像

Lets say instead of name I want to provide a variable field name to this method eg. something like

list.sort(Comparator.comparing(report -> report.anyField))

其中anyField可以是名称,日期或分数.我如何实现此行为.

where anyField can be name or date or score. How do I achieve this behavior.

推荐答案

一种非常通用的解决方案是使用Java的

One very generic solution is to use Java's Reflection and some casting:

    String sortBy = "name";
    list.sort(Comparator.comparing(report -> {
        try {
            return (Comparable) report.getClass().getDeclaredField(sortBy).get(report);
        } catch (Exception e) {
            throw new RuntimeException("Ooops", e);
        }
    }));    

如果您使用 https://github.com/jOOQ/jOOR 这样的附加库,则代码变得更加简单:

If you use an additional library like https://github.com/jOOQ/jOOR the code becomes even simpler:

    String sortBy = "score";
    list.sort(Comparator.comparing(report -> Reflect.on(report).field(sortBy).get()));

请注意,此解决方案仅适用于实现Comparable的字段,并且具有一些运行时开销.

Please be aware that this solution only works with fields that implement Comparable and that it has some runtime overhead.

这篇关于我们如何在Comparator.comparing中传递变量字段/方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆