那个通用的List排序是用在 点击表头排序用的 实现了后就不用在去数据库中查询了 但是代码太 恶心了 但是又想不出跟好的办法了!! 有高手的来帮忙修改一下 !
[code=Java]package pageUtil;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
//T代表任何类型
public class SortUtil<T> implements Comparator<Object>{//本T指将要转换的类 本工具类支持泛型
private static String t;
private static SortUtil su = null;
public static void setParam(String param) {
t=param;
}
public SortUtil(){}
public static <T> SortUtil newInstance(){
su = new SortUtil();
return su;
}
public int compare(Object o1, Object o2) {
T t1 = (T) o1;
T t2 = (T) o2;
Class c1 = t1.getClass();
Class c2 = t2.getClass();
try {
Field f1 = c1.getDeclaredField(t.toString());
Field f2 = c2.getDeclaredField(t.toString());
String typeName= String.valueOf(f1.getType().getSuperclass()==null ? f1.getType().getName() : f1.getType().getSuperclass().getName());
if(typeName.equals("int") || typeName.equals("float") || typeName.equals("double") || typeName.equals("java.lang.Number")){
String value1_1 = EntityCopy.getFieldValue(t1,f1.getName()).toString();
String value1_2 = EntityCopy.getFieldValue(t2,f2.getName()).toString();
int value1 = 0 ;//如果不是浮点型的参数 就取正
int value2 = 0 ;//如果不是浮点型的参数 就取正
int lastNum1 = 0;//末尾小数
int lastNum2 = 0;//末尾小数
if(value1_1.indexOf(".")!=-1){
value1_1 = value1_1.substring(0,value1_1.indexOf("."));
//取末尾小数
lastNum1 = Integer.parseInt(value1_1.substring(value1_1.indexOf(".")+1,value1_1.length()));
}
if(value1_2.indexOf(".")!=-1){
value1_2 = value1_2.substring(0,value1_2.indexOf("."));
//取末尾小数
lastNum2 = Integer.parseInt(value1_2.substring(value1_2.indexOf(".")+1,value1_2.length()));
}
value1 = Integer.parseInt(value1_1)+lastNum1;
value2 = Integer.parseInt(value1_2)+lastNum2;
return value1-value2;
} else if(typeName.equals("char") || typeName.equals("byte") ||typeName.equals("java.lang.String")||typeName.equals("java.lang.Object")) {
//调用EntityCopy类中的 getFieldValue(entity,paramName);
//其中传两个参数 entity(实体类 必须是实例化过的存值对象) paramName 属性名称
String value1 = String.valueOf(EntityCopy.getFieldValue(t1,f1.getName().toString()));
String value2 = String.valueOf(EntityCopy.getFieldValue(t2,f2.getName().toString()));
return value1.compareTo(value2);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return 0;
}
public List mySort(List list){
Collections.sort(list, SortUtil.newInstance());
return list;
}
public List myReverce(List list){
this.mySort(list);
Collections.reverse(list);
return list;
}
//在此调用
// public static void main(String [] args ){
// StudentInfo si1= new StudentInfo("jack",'男',19,52,new Float(49));
// StudentInfo si2= new StudentInfo("mery",'女',18,23,new Float(47));
// StudentInfo si3= new StudentInfo("jim",'男',20,21,new Float(48));
// List<StudentInfo> list = new ArrayList<StudentInfo>();
// list.add(si1);
// list.add(si2);
// list.add(si3);
//
// SortUtil su = SortUtil.newInstance();
// su.setParam("name");
//// su.mySort(list);//取正排序
// su.myReverce(list);//取反排序
// for(Iterator i = list.iterator() ; i.hasNext() ;){
// StudentInfo si = (StudentInfo) i.next();
// System.out.println(si.getName()+" "+si.getSex()+" "+si.getAge()+" "+si.getAge2()+" "+si.getPrice());
// }
// }
}
这个方法是那个通过 实体类名和属性那值的方法//根据实体名称和方法名称方法该方法的值(必须是get方法)
public static Object getFieldValue(Object entity , String propertyName ){
//用字符串的方式把属性转换成get方法
String methodName = "get"+propertyName.toString().substring(0,1).toUpperCase()+propertyName.substring(1,propertyName.length());
//拿到此实体类的类对象
Class c = entity.getClass();
Object obj = null;
Method m = null;
try {
m = c.getDeclaredMethod(methodName, null);
obj = m.invoke(entity,null);
} 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 obj;
}
/code]
[code=Java]package pageUtil;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
//T代表任何类型
public class SortUtil<T> implements Comparator<Object>{//本T指将要转换的类 本工具类支持泛型
private static String t;
private static SortUtil su = null;
public static void setParam(String param) {
t=param;
}
public SortUtil(){}
public static <T> SortUtil newInstance(){
su = new SortUtil();
return su;
}
public int compare(Object o1, Object o2) {
T t1 = (T) o1;
T t2 = (T) o2;
Class c1 = t1.getClass();
Class c2 = t2.getClass();
try {
Field f1 = c1.getDeclaredField(t.toString());
Field f2 = c2.getDeclaredField(t.toString());
String typeName= String.valueOf(f1.getType().getSuperclass()==null ? f1.getType().getName() : f1.getType().getSuperclass().getName());
if(typeName.equals("int") || typeName.equals("float") || typeName.equals("double") || typeName.equals("java.lang.Number")){
String value1_1 = EntityCopy.getFieldValue(t1,f1.getName()).toString();
String value1_2 = EntityCopy.getFieldValue(t2,f2.getName()).toString();
int value1 = 0 ;//如果不是浮点型的参数 就取正
int value2 = 0 ;//如果不是浮点型的参数 就取正
int lastNum1 = 0;//末尾小数
int lastNum2 = 0;//末尾小数
if(value1_1.indexOf(".")!=-1){
value1_1 = value1_1.substring(0,value1_1.indexOf("."));
//取末尾小数
lastNum1 = Integer.parseInt(value1_1.substring(value1_1.indexOf(".")+1,value1_1.length()));
}
if(value1_2.indexOf(".")!=-1){
value1_2 = value1_2.substring(0,value1_2.indexOf("."));
//取末尾小数
lastNum2 = Integer.parseInt(value1_2.substring(value1_2.indexOf(".")+1,value1_2.length()));
}
value1 = Integer.parseInt(value1_1)+lastNum1;
value2 = Integer.parseInt(value1_2)+lastNum2;
return value1-value2;
} else if(typeName.equals("char") || typeName.equals("byte") ||typeName.equals("java.lang.String")||typeName.equals("java.lang.Object")) {
//调用EntityCopy类中的 getFieldValue(entity,paramName);
//其中传两个参数 entity(实体类 必须是实例化过的存值对象) paramName 属性名称
String value1 = String.valueOf(EntityCopy.getFieldValue(t1,f1.getName().toString()));
String value2 = String.valueOf(EntityCopy.getFieldValue(t2,f2.getName().toString()));
return value1.compareTo(value2);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return 0;
}
public List mySort(List list){
Collections.sort(list, SortUtil.newInstance());
return list;
}
public List myReverce(List list){
this.mySort(list);
Collections.reverse(list);
return list;
}
//在此调用
// public static void main(String [] args ){
// StudentInfo si1= new StudentInfo("jack",'男',19,52,new Float(49));
// StudentInfo si2= new StudentInfo("mery",'女',18,23,new Float(47));
// StudentInfo si3= new StudentInfo("jim",'男',20,21,new Float(48));
// List<StudentInfo> list = new ArrayList<StudentInfo>();
// list.add(si1);
// list.add(si2);
// list.add(si3);
//
// SortUtil su = SortUtil.newInstance();
// su.setParam("name");
//// su.mySort(list);//取正排序
// su.myReverce(list);//取反排序
// for(Iterator i = list.iterator() ; i.hasNext() ;){
// StudentInfo si = (StudentInfo) i.next();
// System.out.println(si.getName()+" "+si.getSex()+" "+si.getAge()+" "+si.getAge2()+" "+si.getPrice());
// }
// }
}
这个方法是那个通过 实体类名和属性那值的方法//根据实体名称和方法名称方法该方法的值(必须是get方法)
public static Object getFieldValue(Object entity , String propertyName ){
//用字符串的方式把属性转换成get方法
String methodName = "get"+propertyName.toString().substring(0,1).toUpperCase()+propertyName.substring(1,propertyName.length());
//拿到此实体类的类对象
Class c = entity.getClass();
Object obj = null;
Method m = null;
try {
m = c.getDeclaredMethod(methodName, null);
obj = m.invoke(entity,null);
} 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 obj;
}
/code]
public static Object getFieldValue(Object entity , String propertyName ){
//用字符串的方式把属性转换成get方法
String methodName = "get"+propertyName.toString().substring(0,1).toUpperCase()+propertyName.substring(1,propertyName.length()); //拿到此实体类的类对象
Class c = entity.getClass();
Object obj = null;
Method m = null;
try {
m = c.getDeclaredMethod(methodName, null);
obj = m.invoke(entity,null);
} 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 obj;
}
例如Integer id;
那么id的returnTypeName equals("java.lang.Number")不为true吧?
尤其是long类型不知楼主如何处理的。
如果简化,可以将java常用类型放在枚举中,这样既全面又保证值不失真。
楼主可以尝试代理模式:
将list集合中的对象包装成代理类,把代理类继承于Comparable,并实现compareTo方法(如果原类已继承,则覆盖);
代理类动态改变compareTo方法(取决于前台传来的值);
再用Arrays.sort()和reverse()方法为list排序;
最后将代理类转为原类。cglib工具做代理类很方便的。
反正 那个compareTo方法 是对字符串排序的嘛 然后还有就是 按数字排序呀我就想到了两种啊!
象前面的那个
就是 如果这个类型的抽象类 不是Number型的 那么他就是一个字符串的啦!
在如果他的抽象类是Number类型的“typeName.equals("java.lang.Number"))”
就是说 这个类型是属于数值型的 我就可以按数值型的 大于小于等于来排序啦
因此我只设计了两种排序的方式 字符串的 不管他是 日期还是什么的 都按这个compareTo来拍
String typeName= String.valueOf(f1.getType().getSuperclass()==null ? f1.getType().getName() : f1.getType().getSuperclass().getName());
还有
if(typeName.equals("int") || typeName.equals("float") || typeName.equals("double") || typeName.equals("java.lang.Number")){
然后阁下还说了 代理!! 我对代理不是很用的熟
又兴趣的话 可以加我 共同讨论
qq308117229
String value1_1 = EntityCopy.getFieldValue(t1,f1.getName()).toString();
String value1_2 = EntityCopy.getFieldValue(t2,f2.getName()).toString(); int value1 = 0 ;//如果不是浮点型的参数 就取正
int value2 = 0 ;//如果不是浮点型的参数 就取正 int lastNum1 = 0;//末尾小数
int lastNum2 = 0;//末尾小数
if(value1_1.indexOf(".")!=-1){
value1_1 = value1_1.substring(0,value1_1.indexOf("."));
//取末尾小数
lastNum1 = Integer.parseInt(value1_1.substring(value1_1.indexOf(".")+1,value1_1.length()));
}
if(value1_2.indexOf(".")!=-1){
value1_2 = value1_2.substring(0,value1_2.indexOf("."));
//取末尾小数
lastNum2 = Integer.parseInt(value1_2.substring(value1_2.indexOf(".")+1,value1_2.length()));
}
value1 = Integer.parseInt(value1_1)+lastNum1;
value2 = Integer.parseInt(value1_2)+lastNum2; return value1-value2;
LZ 当一个数长千万之后 它会变成科学计数法的
下面是我改过之后的代码
if(typeName.equals("int") || typeName.equals("float") || typeName.equals("double") || typeName.equals("java.lang.Number")){
BigDecimal b1=BigDecimal.valueOf(Double.valueOf(getFieldValue(t1,f1.getName()).toString()));
BigDecimal b2=BigDecimal.valueOf(Double.valueOf(getFieldValue(t2,f2.getName()).toString()));
return b1.subtract(b2).intValue();还有一些其他的地方有一些小小的改动 成了我的了(*^__^*) 嘻嘻……
private Object getFieldValue(Object entity , String propertyName ){
Object obj=null;
try {
obj=PropertyUtils.getProperty(entity,propertyName);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
其实 最上面的那个
“//调用EntityCopy类中的 getFieldValue(entity,paramName); ”
的getFiledValue方法是我另外写的一个山寨版的
BeanUtils 类 诺 是不是这两个方法:
BeanUtils.copyProperties(dest, orig);
BeanUtils.copyProperty(bean, name, value);我把他强化了一些些了! 分享给大家吧package pageUtil;import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;import javax.servlet.http.HttpServletRequest;public final class EntityCopy{
public EntityCopy(){}
public static EntityCopy newInstance(){
return new EntityCopy();
}
// 目标被设置实体类 源实体类 指定参数(可以不指定 不指定则按源实体类赋值) isFull 为true时表示 源实体类即使是空的也赋值 false 则检查不为空的才赋值
public static void copyEntity_2(Object targetEntity, Object yuanEntity,Object [] param ,boolean isFull){
//目标对象 将要被赋值的对象
Class ct = targetEntity.getClass();
//数据源
Class cy = yuanEntity.getClass();
//拿到目标实体类所有属性
Field [] targetF = cy.getDeclaredFields();
//拿到源实体类所有属性
Field [] yuanF = ct.getDeclaredFields();
for(int i = 0 ; i < targetF.length ; i ++ ){
//根据目标对象需要设置的属性设置值
String targetName = targetF[i].getName(); //重点 *
//如果传进来的参数不为空 则代表指定了参数范围 下面的属性设值则全靠指定参数为标准
for(int j = 0 ; j < (param != null && param.length != 0 ? (param.length) : (yuanF.length)) ; j ++ ){
//拿到源实体类属性名称(因为要根据和其属性值是否为空进行设置 以及根据现有的属性设置 不然则报错)
String yuanName = (param!= null && param.length!=0 && param[j]!=(null)) ? (param[j].toString()) : (yuanF[j].getName());
//调用源实体类对象方法
String value = getFieldValue(yuanEntity, yuanName).toString();
//isFull判断 如果为true 则不验证源实体类属性值是否为空 反之亦然
if(targetName.equals(yuanName) && (isFull ? isFull : value != null && !value.equals(""))){
//判断类型设置目标属性值(其实就是根据其类型创建一个同类型的值出来)
String fieldType = targetF[i].getType().toString();
setFieldValue(fieldType, targetEntity, targetName, value);
}
}
}
}
////通过请求传过来的表单把 表单内与实体类属性相同的copy进实体中 可以代替ActionForm isFull 为true时表示 源实体类即使是空的也赋值 false 则检查不为空的才赋值
public static Object copyPageEntity(Object entity, HttpServletRequest resq,Object[] param, boolean isFull) {
Enumeration e = resq.getParameterNames();
if(e==null){
return null;
}
//拿到所有的类属性
Class c = entity.getClass();
Field [] f = c.getDeclaredFields();
while(e.hasMoreElements()){
//迭代拿到页面传过来的name
String enumName = e.nextElement().toString();
for(int i = 0 ;i < (param!=null && param.length!=0 ? param.length : f.length) ; i++){
//拿到属性名称
String propertyName = ((param!=null && param[i]!=null && param.length!=0) ? param[i].toString() : f [i].getName());
//如果页面传过来的name和实体类的属性name相同
if(propertyName.equals(enumName)){
//则通过请求拿到值
String value = resq.getParameter(enumName); //获得属性的类型
String typeName = "";
try {
typeName = c.getDeclaredField(enumName).getType().toString();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
//根据映射通过此类的方法名称methodName 获得操作权限
if(isFull ? isFull : (value!=null && !value.equals(""))){
//执行方法
setFieldValue(typeName, entity, propertyName, value);
}
}
}
}
return entity;
}
//设置属性值 属性名称 实体类(必须是实例化过的) 要被设置值的方法 值 ---------一般 只是内部实现---------
public static void setFieldValue(String typeName , Object entity, String propertyName ,String value){
//用字符串的方式把属性转换成set方法
String methodName = "set"+propertyName.toString().substring(0,1).toUpperCase()+propertyName.substring(1,propertyName.length());
//拿到该类的类对象
Class clas = entity.getClass();
try{
if(typeName.equals("int")){
clas.getDeclaredMethod(methodName,new Class[]{int.class}).invoke(entity,new Object[]{new Integer(value)});
}else if(typeName.equals("boolean")){
clas.getDeclaredMethod(methodName,new Class[]{boolean.class}).invoke(entity,new Object[]{new Boolean(value)});
}else if(typeName.equals("double")){
clas.getDeclaredMethod(methodName,new Class[]{double.class}).invoke(entity,new Object[]{new Double(value)});
}else if(typeName.equals("float")){
clas.getDeclaredMethod(methodName,new Class[]{float.class}).invoke(entity,new Object[]{new Float(value)});
}else if(typeName.equals("long")){
clas.getDeclaredMethod(methodName,new Class[]{long.class}).invoke(entity,new Object[]{new Long(value)});
}else if(typeName.equals("short")){
clas.getDeclaredMethod(methodName,new Class[]{short.class}).invoke(entity,new Object[]{new Short(value)});
}else if(typeName.equals("String")){
clas.getDeclaredMethod(methodName,new Class[]{String.class}).invoke(entity,new Object[]{value});
}else if(typeName.equals("class java.lang.StringBuffer") || typeName.equals("java.lang.StringBuffer")){
clas.getDeclaredMethod(methodName,new Class[]{StringBuffer.class}).invoke(entity,new Object[]{new StringBuffer(value)});
}
else{
try {
throw new NoSuchPropertyException_2("找不到这样的类型丫丫 可以在上面在设置一种类型丫丫!!");
} catch (NoSuchPropertyException_2 e) {
e.printStackTrace();
}
}
/*
* 编辑区
* 编辑自己定义的类型
*/
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (NumberFormatException e2) {
e2.printStackTrace();
} catch (IllegalArgumentException e3) {
e3.printStackTrace();
} catch (IllegalAccessException e4) {
e4.printStackTrace();
} catch (InvocationTargetException e5) {
e5.printStackTrace();
}
}
//根据实体名称和方法名称方法该方法的值(必须是get方法)
public static Object getFieldValue(Object entity , String propertyName ){
//用字符串的方式把属性转换成get方法
String methodName = "get"+propertyName.toString().substring(0,1).toUpperCase()+propertyName.substring(1,propertyName.length());
//拿到此实体类的类对象
Class c = entity.getClass();
Object obj = null;
Method m = null;
try {
m = c.getDeclaredMethod(methodName, null);
obj = m.invoke(entity,null);
} 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 obj;
}
//测试
public static void main(String [] args) {
PageEntity pe = new PageEntity();
pe.setForwardPath(new StringBuffer("O(∩_∩)O哈哈~"));
pe.setCurrentPage(6);
pe.setRowCount(600);
PageEntity pe2 = new PageEntity();
pe2.setMaxRow(60000);
EntityCopy ec = new EntityCopy();
//new Object[]{"forwardPath","currentPage"}
ec.copyEntity_2(pe2, pe, new Object[]{"forwardPath","currentPage"}, true);
System.out.println("getCurrentPage:"+pe2.getCurrentPage()+" getForwardPath:"+pe2.getForwardPath()+ " getRowCount:"+pe2.getRowCount()+" getMaxRow:"+pe2.getMaxRow()+" getPageCount:"+pe2.getPageCount());
}
}
/*
* 自己定义异常
*/
class NoSuchMethodException_2 extends Exception {
public NoSuchMethodException_2(String msg){
super(msg);
}
}
class NoSuchPropertyException_2 extends Exception {
public NoSuchPropertyException_2(String msg){
super(msg);
}
}
你不同的排序 貌似只要传入不同的comparator就可以了吧
Collections.sort(List<T> list, Comparator<? super T> c)