Java provides Comparable interface to help you sort the items in the collections.
However, if you want to dynamically decide the field to sort the collection, try this dynamic comparator
import java.lang.reflect.Method;
import java.util.Comparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DynamicComparator<T> implements Comparator<T> {
private static final Log LOG = LogFactory.getLog(DynamicComparator.class);
private final Class[] nullclazz = new Class[] {};
private final Object[] nullargs = new Object[] {};
private Method method;
private String returnType;
public DynamicComparator(Class class1, String fieldName)
throws SecurityException, NoSuchMethodException {
this.method = getMethod(class1, "get", fieldName);
this.returnType = method.getReturnType().getName();
}
public int compare(T o1, T o2) {
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null || o2 == null) {
return o1 == null ? -1 : 1;
} else {
try {
if ("java.lang.String".equals(returnType)) {
return ((String) method.invoke(o1, nullargs))
.compareTo((String) method.invoke(o2, nullargs));
}
if ("int".equals(returnType)) {
return ((Integer) method.invoke(o1, nullargs))
.compareTo((Integer) method.invoke(o2, nullargs));
}
if ("double".equals(returnType)) {
return ((Double) method.invoke(o1, nullargs))
.compareTo((Double) method.invoke(o2, nullargs));
}
} catch (Exception e) {
LOG.error(e);
}
}
return 0;
}
private Method getMethod(Class clazz, String prefix, String fieldName) {
String methodName = prefix + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
return clazz.getMethod(methodName, nullclazz);
} catch (Exception e) {
LOG.error(e);
}
return null;
}
}
To use this class:
Collection c = //the collection you want to sort.
List list = new ArrayList(c);
DynamicComparator comparator = new DynamicComparator(list.get(0).getClass(), "fieldName");
Collections.sort(list, comparator);
沒有留言:
張貼留言