Java Comparator given the name of the property to compare(Java Comparator 给出要比较的属性的名称)
问题描述
我的问题是这样的;我必须订购一张数据表.表格的每一行都是一个存储在列表中的对象(我们称之为 TableObject).每列数据都是类的一个属性(通常是一个字符串).
My problem is this; I have to order a table of data. Each row of the table is an object (lets call it TableObject) stored in a List. Each column of data is a property of the class (usually a String).
当用户单击任何列时,我必须对数据进行典型的排序.所以我考虑将 List 更改为 TreeSet 并在我的 TableObject 中实现 Comparator.
I have to do the typical ordering of data when the user clicks on any column. So I thought about changing the List to a TreeSet and implementing Comparator in my TableObject.
当我尝试重新排序 TreeSet 时,问题就出现了.比较一开始相当容易(在 parseInt 中检查异常已被省略):
The problem comes when I try to reorder the TreeSet. The compare is fairly easy at first (cheeking for exceptions in parseInt have been omitted):
public int compare(TableObject to1, TableObject to2){
TableObject t1 = to1;
TableObject t2 = to2;
int result = 1;
if(Integer.parseInt(t1.getId()) == Integer.parseInt(t2.getId())){result=0;}
if(Integer.parseInt(t1.getId()) < Integer.parseInt(t2.getId())){result=-1;}
return result;
}
但是当我必须按数据文本或 TableObject 拥有的其他数十个数据重新排序时,我遇到了问题.我不想创建几十个比较函数,每个函数对应一个.我不喜欢使用开关(或 if 链)来决定如何比较对象.
But when I have to reorder by the text of the data or by other dozens of data that the TableObject has I have a problem. I do not want to create dozens of compare functions, each for one. I prefer not to use a switch (or a chain of ifs) to decide how to compare the object.
有没有办法以某种方式做到这一点(如 Reflexive),这并不意味着我会编写数百行几乎相同的代码?
Is there any way to do this in some way (like Reflexive), that doesn't imply that I will write like hundreds of lines of nearly the same code?
谢谢大家!
推荐答案
Bean Comparator 应该可以工作.
使用 BeanComparator
的反射,这将允许您对具有返回属性值的零参数方法的任何属性进行排序.
Using reflection the BeanComparator
that will allow you to sort on any property that has a zero parameter method that returns the value of the property.
所以基本上你可以对任何具有getter"的属性进行排序.方法.
So basically you can sort on any property that has a "getter" method.
这篇关于Java Comparator 给出要比较的属性的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Comparator 给出要比较的属性的名称


基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01