Java2个对象字段值比较是否相同

时间:2025-04-22 21:02:41

1、工具类

package ;

/**
 * @author tqf
 * @Description
 * @Version 1.0
 * @since 2022-03-21 16:50
 */

import ;

import ;
import ;
import ;

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(!().isAssignableFrom(())){
            throw new RuntimeException("两个对象不相同,无法比较");
        }

        //取出属性
        Field[] beforeFields = ().getDeclaredFields();
        Field[] afterFields = ().getDeclaredFields();
        (beforeFields, true);
        (afterFields, true);

        //遍历取出差异值
        if(beforeFields != null &&  > 0){
            for(int i=0; i<; i++){
                Object beforeValue = beforeFields[i].get(beforeObj);
                Object afterValue = afterFields[i].get(afterObj);
                if((beforeValue != null && !"".equals(beforeValue) && !(afterValue)) || ((beforeValue == null || "".equals(beforeValue)) && afterValue != null)){
                    Comparison comparison = new Comparison();
                    (beforeFields[i].getName());
                    (beforeValue);
                    (afterValue);
                    (true);
                    (comparison);
                }
            }
        }

        return diffs;
    }
}
 public static void main(String[] args) throws Exception {
        ApIData apIData = new ApIData()
                .setName("张三")
                .setMonth("5")
                .setHh("1");
        ApIData apIData1 = new ApIData()
                .setName("张三")
                .setMonth("9")
                .setHh("35");
        List<Comparison> list = (apIData, apIData1);
        //遍历删除 
        Iterator<Comparison> iterator = ();
        while (()) {
            Comparison comparison = ();
            switch (()){
                case "createTime" :
                case "updateTime" :
                case "id":
                    // 使用迭代器的删除方法删除
                    ();
                    break;
            }
        }        
        (list);
    }
package ;

import ;
import ;

/**
 * @author tqf
 * @Description  接口请求参数类
 * @Version 1.0
 * @since 2020-08-03 20:06
 */
@Data
@Accessors(chain = true) //注解用来配置lombok如何产生和显示getters和setters的方法
public class ApIData {

    /**
     * 身份证号
     */
    private String ident_card;

    /**
     * 姓名
     */
    private String name;

    /**
     * 户号  水务局使用查询
     */
    private String hh;

    /**
     * 用水月份  YYYY-MM
     */
    private String month;

    /**
     * 房东用户ID
     */
    private String owner_id;

    /**
     * 所属街道
     */
    private String street_name;




}