• 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;
        }
    }
  • 相关阅读:
    ASP.NET Core 中的路由约束
    专治拖延症,好方法
    虚拟机hadoop集群搭建
    python爬虫+词云图,爬取网易云音乐评论
    gp数据库运维
    kafka和springboot整合应用
    kafka配置监控和消费者测试
    集群运维ansible
    SpringBoot和微服务
    python每天定时发送短信脚本
  • 原文地址:https://www.cnblogs.com/i-tao/p/14518960.html
Copyright © 2020-2023  润新知