码迷,mamicode.com
首页 > 其他好文 > 详细

对象比较

时间:2016-08-21 15:21:15      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

对象比较

标签:

原文地址:http://www.cnblogs.com/booth-sun/p/5792729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!