java 通用对象_java 通用对象排序

  • Post author:
  • Post category:java


packageutil;importjava.lang.reflect.Field;importjava.util.Comparator;

@SuppressWarnings(“rawtypes”)public class ComparatorUtil implementsComparator{//要排序的属性名

privateString name;//是否升序

private boolean falg = true;/***@paramname 要排序的属性名,如果是基本类型的排序,请入null值

*@paramfalg false/true : 升序/降序*/

public ComparatorUtil(String name, booleanfalg) {super();this.name =name;this.falg =falg;

}

@Overridepublic intcompare(Object o1, Object o2) {int result = 0;//入参为空|参数类型不相等,都不进行处理。

if(o1 == null || o2 == null || !o1.getClass().getName().equals(o2.getClass().getName())){returnresult;

}//7大基本类型的处理(boolean除外.且把Collections.reverse()/Collections.sort()的事也做了)

if(isBaseType(o1)){//比较

returnbaseTypeOpt(o1,o2);

}try{

Field f1=o1.getClass().getDeclaredField(name);

Field f2=o2.getClass().getDeclaredField(name);//设置private可读

f1.setAccessible(true);

f2.setAccessible(true);

result=baseTypeOpt(f1.get(o1),f2.get(o2));

}catch (Exception e) { //异常懒得处理了,如果没有对应的属性,那就不排序了.(手动滑稽)

e.printStackTrace();

}returnresult;

}private intbaseTypeOpt(Object o1, Object o2) {int result = 0;if(o1 instanceofString){

result=o1.toString().compareTo(o2.toString());

}else if(o1 instanceofInteger){

result= ((Integer)o1) -((Integer)o2);

}else if(o1 instanceofDouble){if(((Double)o1 – (Double)o2) > 0){

result= 1;

}else if(((Double)o1 – (Double)o2) < 0){

result= -1;

}

}else if(o1 instanceofFloat){if(((Float)o1 – (Float)o2) > 0){

result= 1;

}else if(((Float)o1 – (Float)o2) < 0){

result= -1;

}

}else if(o1 instanceofCharacter){

result=((Character)o1).compareTo(((Character)o2));

}else if(o1 instanceofShort){

result= ((Short)o1) -((Short)o2);

}else if(o1 instanceofLong){if(((Long)o1 – (Long)o2) > 0){

result= 1;

}else if(((Long)o1 – (Long)o2) < 0){

result= -1;

}

}//降序

if(isFalg()){

result= -result;

}returnresult;

}private booleanisBaseType(Object o) {if((o instanceof String) || (o instanceofInteger)|| (o instanceof Double) || (o instanceofFloat)|| (o instanceof Character) || (o instanceofShort)|| (o instanceofLong)){return true;

}return false;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public booleanisFalg() {returnfalg;

}public void setFalg(booleanfalg) {this.falg =falg;

}

}



版权声明:本文为weixin_29166013原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。