【Java】对于自定义对象List进行排序

来源:互联网 发布:json好处 编辑:程序博客网 时间:2024/05/19 01:08

  做页面列表排序的时候很容易遇到如题的用法,一般针对自定义对象的某一属性进行列表排序,自定义属性一般有多个属性,如果要排序的属性比较少(1个或2个),可以写两种比较,当然我们有更好的方法,java class类提供了getDeclaredMethod可以通过对象的方法名获取Method对象,再通过Method的invoke方法就可以调用此对象的方法。

  比如有一个Account对象有一String类型的属性aID方法名字叫getAID(),我们可以通过以下方法获取到此aID的值

  Account test = new Account();

  Method m = test.getClass().getDeclaredMethod("getAID", null);

  String testID = (String) m.invoke(test, null);

  其实这样就可以解决根据属性名来获取属性值。排序的完整代码如下:

  使用 sort(accountList, "AID", "asc");

 

private void sort(List<Account> accountList, String orderField,String orderDirection) {if("desc".equals(orderDirection) || "asc".equals(orderDirection)) {final String methodName = "get" + orderField;final String type = orderDirection;Collections.sort(accountList,  new Comparator<Account>() {public int compare(Account a, Account b) {int ret = 0;try {Method m = a.getClass().getDeclaredMethod(methodName, null);try {String aStr = (String) m.invoke(a, null);String bStr = (String) m.invoke(b, null);ret = aStr.compareTo(bStr);ret = "asc".equals(type)?ret:-ret;} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}} catch (SecurityException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}return ret;}});} 


 



原创粉丝点击