/** * 利用java反射机制进行排序 * @param myClass 集合中的对象 * @param sortList 需要排序的集合 * @param fieldName 对象中的属性 */ public static void myComparator(final Object myClass, List sortList, final String fieldName) { Collections.sort(sortList, new Comparator() { public int compare(Object o1, Object o2) { try { //根据传过来的字段构造get方法 String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); //得到Method对象 Method method = myClass.getClass().getMethod(methodName, new Class[] {}); //Method反射得到具体的值 Object result1 = method.invoke(o1, new Class[] {}); Object result2 = method.invoke(o2, new Class[] {}); //判断值类型则相应的比较 if (result1 != null && result2 != null && !result1.equals("") && !result2.equals("")) { if (result1 instanceof Double || result1 instanceof Integer || result1 instanceof Float) { if (Double.parseDouble(result1.toString()) > Double.parseDouble(result2.toString())) { return 1; } else { return -1; } } if (result1 instanceof String) { return result1.toString().compareTo(result2.toString()); } if (result1 instanceof Integer) { return ((Integer)result1).intValue()-((Integer)result2).intValue(); } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return 0; } }); }