package com.daojia.beauty.open.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Comparator; /** * 数据比较<br /> */ public class CompareUtil { private static final Logger LOGGER = LoggerFactory.getLogger(CompareUtil.class); /** * 数据比较 * @param compare1 * @param compare2 * @param <T> * @return 0-->相等 , >0 小于 , <0 大于 , null --> 异常情况 */ public static <T> Integer compare(T compare1 , T compare2 ) { if(compare1.getClass() != compare2.getClass()) { throw new RuntimeException("参与比较的两个对象必须属于一个类"); } Method method = IsComparable(compare1.getClass()) ; Integer results = null ; if(method == null) { throw new UnsupportedOperationException("当前类没有实现Comparable或Comparator接口"); } try { results = (Integer)method.invoke(compare1, compare2); return results; }catch (Exception e) { LOGGER.error("反射比较对象大小出现异常",e); } return results; } /** * 判断是否可比较 * @return */ private static Method IsComparable(Class cls) { Class[] interfaces = cls.getInterfaces(); Method method = null; try { for (Class cs : interfaces) { if (cs == Comparable.class) { method = cls.getMethod("compareTo", cls); } if (cs == Comparator.class) { method = cls.getMethod("compare",cls); } } } catch (Exception exception) { exception.printStackTrace(); } return method; } }
时间: 2024-11-08 04:28:18