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.
相关文章