Java:比較兩個對象中所有屬性值是否相等

例以下述Java類:java

import java.io.Serializable;
import java.util.List;

public class Bean_Topology implements Serializable {
	private static final long serialVersionUID = 1L;
	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	private Long topology_pk;

	private String topology_id;

	public String getTopology_id() {
		return topology_id;
	}

	public void setTopology_id(String topology_id) {
		this.topology_id = topology_id;
	}

	public Long getTopology_pk() {
		return topology_pk;
	}

	public void setTopology_pk(Long topology_pk) {
		this.topology_pk = topology_pk;
	}

	@Override
	public String toString() {
		return "當前拓撲的PK爲:" + topology_pk + ",ID爲:" + topology_id;
	}
}
複製代碼

 以下想判斷下面兩個對象中所有屬性值是否一致時,有哪些辦法呢? sql

Bean_Topology topology1 = new Bean_Topology();
	topology1.setTopology_id("1");

Bean_Topology topology2 = new Bean_Topology();
	topology2.setTopology_pk(1L);
	topology2.setTopology_id("1");
複製代碼

方法一:重寫Bean_Topology的equals方法和hashcode方法,代碼以下: bash

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
		
    if (obj == null || getClass() != obj.getClass()) {
        return false;
     }

    Bean_Topology topology = (Bean_Topology) obj;
    if (topology_pk == null) {
        if (topology.topology_pk != null) {
            return false;
        } 
    }else if (!topology_pk.equals(topology.topology_pk)) {
        return false;	
    }
        
    if (topology_id == null) {
        if (topology.topology_id != null) {
            return false;
        } 
    }else if (!topology_id.equals(topology.topology_id)) {
        return false;	
    }
        
        return true;
    }
	
    @Override
    public int hashCode() {
        return  topology_pk.hashCode()+topology_id.hashCode();
    }
複製代碼

測試代碼以下:ide

if(topology1.equals(topology2)) {
	System.out.println("對象1與對象2的屬性值無差別。");
}else {
	System.out.println("對象1與對象2的屬性值有差別。");	
}複製代碼

輸出結果爲: 工具

對象1與對象2的屬性值有差別。複製代碼

方法二:調用文章末尾的工具類,代碼以下: 測試

Map<String, Map<String,Object>> resultMap=compareFields(topology1,topology2);
int size=resultMap.size();
if(size>0) {
    System.out.println("對象1與對象2的屬性值有差別,差別結果以下:");
		
    Iterator<String> it = resultMap.keySet().iterator();
    while(it.hasNext()) {
        String key=it.next();
        System.out.println(" "+key+"(oldValue:"+resultMap.get(key).get("oldValue")+",newValue:"+resultMap.get(key).get("newValue")+")");
        }	
}else {
	System.out.println("對象1與對象2的屬性值無差別!");
}複製代碼

輸出結果爲:  ui

對象1與對象2的屬性值有差別,差別結果以下:
  topology_pk(oldValue:null,newValue:1)複製代碼

工具類以下: this

package com.sitech.modual.util.compare;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.sitech.modual.bean.Bean_Link;
import com.sitech.modual.bean.Bean_Topology;

public class ClassCompareUtil {
	/**
	 * 比較兩個實體屬性值,返回一個boolean,true則表時兩個對象中的屬性值無差別
	 * @param oldObject 進行屬性比較的對象1
	 * @param newObject 進行屬性比較的對象2
	 * @return 屬性差別比較結果boolean
	 */
	public static boolean compareObject(Object oldObject, Object newObject) {
		Map<String, Map<String,Object>> resultMap=compareFields(oldObject,newObject);
		
		if(resultMap.size()>0) {
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * 比較兩個實體屬性值,返回一個map以有差別的屬性名爲key,value爲一個Map分別存oldObject,newObject此屬性名的值
	 * @param oldObject 進行屬性比較的對象1
	 * @param newObject 進行屬性比較的對象2
	 * @return 屬性差別比較結果map
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Map<String,Object>> compareFields(Object oldObject, Object newObject) {
		Map<String, Map<String, Object>> map = null;
		
		try{	
			/**
			 * 只有兩個對象都是同一類型的纔有可比性
			 */
			if (oldObject.getClass() == newObject.getClass()) {
				map = new HashMap<String, Map<String,Object>>();
				
				Class clazz = oldObject.getClass();
				//獲取object的全部屬性
				PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz,Object.class).getPropertyDescriptors();
				
				for (PropertyDescriptor pd : pds) {
					//遍歷獲取屬性名
					String name = pd.getName();
					
					//獲取屬性的get方法
					Method readMethod = pd.getReadMethod();
					
					// 在oldObject上調用get方法等同於得到oldObject的屬性值
					Object oldValue = readMethod.invoke(oldObject);
					// 在newObject上調用get方法等同於得到newObject的屬性值
					Object newValue = readMethod.invoke(newObject);
					
					if(oldValue instanceof List){
						continue;
					}
					
					if(newValue instanceof List){
						continue;
					}
					
					if(oldValue instanceof Timestamp){
						oldValue = new Date(((Timestamp) oldValue).getTime());
					}
					
					if(newValue instanceof Timestamp){
						newValue = new Date(((Timestamp) newValue).getTime());
					}
					
					if(oldValue == null && newValue == null){
						continue;
					}else if(oldValue == null && newValue != null){
						Map<String,Object> valueMap = new HashMap<String,Object>();
							valueMap.put("oldValue",oldValue);
							valueMap.put("newValue",newValue);
						
						map.put(name, valueMap);
						
						continue;
					}
					
					if (!oldValue.equals(newValue)) {// 比較這兩個值是否相等,不等就能夠放入map了
						Map<String,Object> valueMap = new HashMap<String,Object>();
							valueMap.put("oldValue",oldValue);
							valueMap.put("newValue",newValue);
						
						map.put(name, valueMap);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return map;
	}

}複製代碼

注意:本工具類不適用於比較包含List,Map等類的Class。 
spa

最後

歡迎你們有興趣的能夠關注個人公衆號【java小瓜哥的分享平臺】,文章都會在裏面更新,還有各類java的資料都是免費分享的。但願與你們一塊兒進步努力!code

相關文章
相關標籤/搜索