java對比兩個對象字段值差異


1.差異模型

@Data
public class Comparison implements Serializable {
    //字段
    private String Field;
    //字段舊值
    private Object before;
    //字段新值
    private Object after;
}

2.對比類

import com.oigit.api.model.bo.Comparison;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CompareObjUtil {

    public static List<Comparison> compareObj(Object beforeObj, Object afterObj) throws Exception{
        List<Comparison> diffs = new ArrayList<>();
        
        if(beforeObj == null) {
            throw new RuntimeException("原對象不能為空");
        }
        if(afterObj == null) {
            throw new RuntimeException("新對象不能為空");
        }
        if(!beforeObj.getClass().isAssignableFrom(afterObj.getClass())){
            throw new RuntimeException("兩個對象不相同,無法比較");
        }
        
        //取出屬性
        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);
                        diffs.add(comparison);
                    }
            }
        }
        
        return diffs;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM