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

  做页面列表排序的时候很容易遇到如题的用法,一般针对自定义对象的某一属性进行列表排序,自定义属性一般有多个属性,如果要排序的属性比较少(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;
				}
			});
		} 


 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zfpigpig

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值