list中不同实体 根据相同字段排序

/**
	 * 排序方法
	 * @param targetList 要排序的对象
	 * @param sortField 用哪个字段排序
	 * @param sortMode 倒序desc还是正序asc
	 */
	@SuppressWarnings("unchecked")
	public static void sort(List<Object> targetList, String sortField, String sortMode) {  
	    //使用集合的sort方法  ,并且自定义一个排序的比较器
		 Collections.sort(targetList, new Comparator<Object>() { 	
			 	//匿名内部类,重写compare方法 
	            public int compare(Object obj1, Object obj2) {   
	                int result = 0;  
	                try {  
	                    //首字母转大写  
	                    String newStr = sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\w","");   
	                    //获取需要排序字段的“get方法名”
	                    String methodStr = "get"+newStr;  
	                    /**	API文档::
	                     *  getMethod(String name, Class<?>... parameterTypes)
	                     *  返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
	                     */
	                    Method method1 = obj1.getClass().getMethod(methodStr, null);  
	                    Method method2 = obj2.getClass().getMethod(methodStr, null);  
	                    Object returnObj1 = method1.invoke((obj1), null);
	                    Object returnObj2 = method2.invoke((obj2), null);
	                    result = (Integer)returnObj1 - (Integer)returnObj2;
	                } catch (Exception e) {  
	                    throw new RuntimeException();  
	                }  
	                if ("desc".equals(sortMode)) {
                        // 倒序
                        result = -result;
                    }
	                return result;  
	            }  
	        });  
	    }

要是没有get方法 可以用用字段反射获取对应值  至于怎么写自己查去网上一堆 唯一注意的是获取private属性值是要先开启访问权限  实际上setAccessible是启用和禁用访问安全检查的开关

值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查

setAccessible(true)

设置访问权限 不止是字段  方法也是同样的

method.setAccessible(true);

field.setAccessible(true);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值