zoukankan      html  css  js  c++  java
  • CompareUtil

    java
    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);
    
        /**
         *
         */
        private CompareUtil() {
    
        }
        /**
         * 数据比较
         * @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 IllegalArgumentException("参与比较的两个对象必须属于一个类");
            }
    
            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) {
                LOGGER.error("反射获取比较对象的compareTo和compare方法出错",exception);
            }
            return method;
        }
    }
  • 相关阅读:
    SQLite 与 SqlCE 比较
    window.showModalDialog以及window.open用法简介
    Flex 3D Engine演示 帅呆了。
    MySQLFront
    数据库复制相同表语句
    org.jboss.web.jsf.integration.config.JBossJSFConfigureListener
    PHP中全局变量$_SERVER的详细用法
    PHP date函数使用说明
    如何学习Flex Framework
    richfaces a4j标签帮助文档 地址
  • 原文地址:https://www.cnblogs.com/boothsun/p/5842759.html
Copyright © 2011-2022 走看看