/** * @Title: CompareObjUtil.java * @Package cc.messcat.common.util * @Description: TODO * @author limh * @date 2017年3月2日 */ package cc.messcat.util;java import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;this import cc.messcat.vo.Comparison;spa /** * ClassName: 對象比較類 * @Description: TODO * @author limh * @date 2017年3月2日 */ public class CompareObjUtil {.net public static List<Comparison> compareObj(Object beforeObj,Object afterObj) throws Exception{ List<Comparison> differents = new ArrayList<Comparison>(); if(beforeObj == null) throw new Exception("原對象不能爲空"); if(afterObj == null) throw new Exception("新對象不能爲空"); if(!beforeObj.getClass().isAssignableFrom(afterObj.getClass())){ throw new Exception("兩個對象不相同,沒法比較"); } //取出屬性 Field[] beforeFields = beforeObj.getClass().getDeclaredFields(); Field[] afterFields = afterObj.getClass().getDeclaredFields(); Field.setAccessible(beforeFields, true); Field.setAccessible(afterFields, true); //遍歷取出差別值 if(beforeFields != null && beforeFields.length > 0){ for(int i=0; i<beforeFields.length; i++){ Object beforeValue = beforeFields[i].get(beforeObj); Object afterValue = afterFields[i].get(afterObj); if((beforeValue != null && !"".equals(beforeValue) && !beforeValue.equals(afterValue)) || ((beforeValue == null || "".equals(beforeValue)) && afterValue != null)){ Comparison comparison = new Comparison(); comparison.setField(beforeFields[i].getName()); comparison.setBefore(beforeValue); comparison.setAfter(afterValue); differents.add(comparison); } } } return differents; } } 對象 |