簡單DTO對象比較工具類

因工作需要對兩個數據庫表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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章