Hi,
I have just implemented a generic routine for sorting, instead of
having to ask for every column's name, as implemented in the simple
examples from MyFaces (which I understand are only to show how can
things be achieved ;-)
protected void sort(final String column, final boolean ascending,
List listModel)
{
Comparator comparator = new Comparator()
{
public int compare(Object o1, Object o2)
{
if (column == null)
{
return 0;
}
else
{
// Make use of reflection (from
Apache Commmon BeanUtils)
// to determine the type of the
column to be ordered.
try
{
// If and only
if the type is Boolean...
if
(PropertyUtils.getPropertyType(o1, column)
.isAssignableFrom(Boolean.class))
{
return ascending ? PropertyUtils.getProperty(o1,
column).equals(
PropertyUtils.getProperty(o2, column)) ? 0
: 1 :
PropertyUtils.getProperty(o2, column)
.equals(
PropertyUtils.getProperty(o1,
column)) ? 0 : -1;
}
else
{
Object obj1 = PropertyUtils.getProperty(o1, column);
Object obj2 = PropertyUtils.getProperty(o2, column);
// If and only if the type
is Comparable...
if (obj1 instanceof Comparable)
{
return ascending ? ((Comparable)
obj1)
.compareTo(obj2) : ((Comparable) obj2)
.compareTo(obj1);
}
return 0;
}
}
catch (IllegalAccessException e)
{
throw new
BusinessException(e);
}
catch (InvocationTargetException
e)
{
throw new
BusinessException(e);
}
catch (NoSuchMethodException e)
{
throw new
BusinessException(e);
}
}
}
};
// Here you will have to indicate your list to be ordered...
Collections.sort(myListToBeOrdered, comparator);
}
Hope someone finds it useful!
- Generic routine for sorting Enrique Medina
- Re: Generic routine for sorting Enrique Medina
- Re: Generic routine for sorting Enrique Medina

