Answer the question
In order to leave comments, you need to log in
How to compare generic type objects?
Task: Sort objects by property with custom annotation Stuck
while comparing two objects, can't get property value with field.get(obj) nor use compareTo() because they don't work with generics. types.
PS If this task is solved only by using some interface, please advise where you can read about it
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
public class ASort<T>{
public void SortByAnatation(ArrayList<T> tList) {
Field[] fields = tList.get(0)
.getClass()
.getFields();
Field anotatedF = null;
for (Field field : fields) {
if(field.isAnnotationPresent(SortAnatation.class)) {
anotatedF = field;
break;
}
}
if(anotatedF == null) {
System.out.println("Not anotated!");
return;
}
boolean isSorted = false;
T buf;
for(;!isSorted;) {
isSorted = true;
for (int i = 0; i < tList.size()-1; i++) {
if(compareBy(tList.get(i), tList.get(i+1), anotatedF) == 1){
isSorted = false;
buf = tList.get(i);
tList.set(i, tList.get(i + 1));
tList.set(i+1, buf);
}
}
}
}
public int compareBy(T o1, T o2, Field compareF) {
Class<?> fType = compareF.getType();
if(fType==Byte.class||fType==Character.class||fType==Long.class||fType==Integer.class
||fType==String.class||fType==Double.class||fType==Boolean.class) {
return (compareF.get(o1)).compareTo(compareF.get(o2)); // Не компилируется,
//оставил для примера
}
}
}
<code lang="java">
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question