Java Comparator gives property name for comparison

My problem is this; I have to order a data table. Each row of the table is an object (allows you to call it TableObject), stored in the list. Each data column is a property of a class (usually a String).

I have to do a typical data order when the user clicks on any column. So I thought about changing the list in TreeSet and implementing Comparator in my TableObject application.

The problem occurs when I try to reorder the TreeSet. Comparison is pretty straightforward at first (cheeks for exceptions in parseInt were 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; } 

But when I have to reorder by text data or other dozens of data that have a TableObject, I have a problem. I do not want to create dozens of comparison functions, each for one. I prefer not to use a switch (or an ifs chain) to decide how to compare the object.

Is there a way to do this somehow (e.g. Reflexive), which doesn’t mean that I will write like hundreds of lines of almost the same code?

Thanks everyone!

+4
source share
3 answers

Bean Comparator should work.

+5
source

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

Then you can use reflection to sort by a given parameter.

The following code is very dirty. But I think this illustrates the essence of what you will 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"); } } } 
+3
source

Yes, you can use the reflection API to get the contents of a field based on its name.

See the Field class, and especially Field.get .

(I would not recommend it, since reflection is not intended for this type of task.)

+1
source

All Articles