[Ejtools-cvs] libraries/adwt/src/resources New Text Document.txt,NONE,1.1
Brought to you by:
letiemble
From: <let...@us...> - 2002-06-10 07:25:33
|
Update of /cvsroot/ejtools/libraries/adwt/src/resources In directory usw-pr-cvs1:/tmp/cvs-serv8121/adwt/src/resources Added Files: New Text Document.txt Log Message: Pretty Print --- NEW FILE: New Text Document.txt --- package com.bytespinners.util; /** * I searched Google, JGuru, java.sun.com, hustler, and every place I could think of * to see if someone had made a utility to sort a vector of data beans by their value. * It seemed like such a useful idea, that I stayed up late one night and just had a go * at it. I saw it as a change to learn the reflection api, which I had not previously * worked with. I hope others out there might find it useful. * @author Matt Wingle * @company ByteSpinners, Inc. * @date 01-Jan-2002 10:51pm * */ public class BeanSorter { /** * Overloaded method that just returns a comparator that will sort by the specified value ascending * @param bean The type of JavaBean that is in the collection you want to sort * @param propertyName The property of the bean you want to sort by */ public static java.util.Comparator getComparator( Class bean, String propertyName ) { return getComparator( bean, propertyName, true ); } /** * Provide this method with your bean class and the value you want to sort by, and it will return a * fine Comparator that can be used for Sorts, Trees, Maps, and other naturally ordered collections. * You must also pass in a boolean that sorts the list ascending if true, descending if false. * @param bean The type of JavaBean that is in the collection you want to sort * @param propertyName The property of the bean you want to sort by * @param ascending True to sort ascending, false to sort descending */ public static java.util.Comparator getComparator( Class bean, String propertyName, final boolean ascending ) { java.util.Comparator retVal = null; try { final java.beans.PropertyDescriptor pd = new java.beans.PropertyDescriptor( propertyName, bean ); final java.lang.reflect.Method m = pd.getReadMethod(); retVal = new java.util.Comparator() { public int compare( Object a, Object b ) { int retVal = 0; Comparable aVal = null; Comparable bVal = null; try { aVal = (Comparable) m.invoke( a, new Object[0] ); bVal = (Comparable) m.invoke( b, new Object[0] ); } catch ( Exception e ) { e.printStackTrace(); retVal = 0; } if ( aVal == null ) { retVal = -1; } else if ( bVal == null ) { retVal = 1; } else { try { if ( aVal instanceof String && bVal instanceof String ) { retVal = ( ((String)aVal).toUpperCase()).compareTo( ((String)bVal).toUpperCase() ); } else { retVal = aVal.compareTo( bVal ); } } catch (Exception e) { e.printStackTrace(); } } return ascending ? retVal : -1 * retVal; } }; } catch ( Exception e ) { e.printStackTrace(); } return retVal; } } |