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;
    }
}
原文地址:https://www.cnblogs.com/i-tao/p/14518960.html