简单DTO对象比较工具类

  • Post author:
  • Post category:其他


因工作需要对两个数据库表DTO对象进行比较。

public class CompareFacility {

    public static boolean objectEqualsTo(Object t1,Object t2){
        boolean result = true;
        if( t1 == null || t2 == null){
            throw new NullPointerException();
        }

        if(!t1.getClass().getName().equals(t2.getClass().getName())){
            return false;
        }

        if(t1.getClass().isPrimitive()){
            return t1 == t2;
        }

        if(t1 instanceof Comparable){
            return ((Comparable) t1).compareTo(t2) == 0;
        }

        Field[] fields = t1.getClass().getDeclaredFields();
        try{
            for (Field field : fields){
                field.setAccessible(true);
                Field field2 =t2.getClass().getDeclaredField(field.getName());
                field2.setAccessible(true);
                Object v1 = field.get(t1);
                Object v2 = field2.get(t2);
                if(!v1.equals(v2)){
                    result = false;
                }
            }
        }catch (Exception e){
            throw new RuntimeException("对象比较失败");
        }
        return result;
    }
}



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