How to compare the values of two object fields in Java to see if they are the same?
This article mainly introduces Java 2 object field values how to compare whether the same related knowledge, detailed and easy to understand, simple and fast operation, has a certain reference value, I believe we read this Java 2 object field values how to compare whether the same article will have some gains, let's take a look at it.
tools package com.shucha.deveiface.biz.utils; /** * @author tqf * @Description * @Version 1.0 * @since 2022-03-21 16:50 */ import com.shucha.deveiface.biz.model.Comparison; import java.lang.reflect.Field;import java.util.ArrayList;import java.util.List; public class CompareObjUtil { public static List compareObj(Object beforeObj, Object afterObj) throws Exception{ List diffs = new ArrayList(); if(beforeObj == null) { throw new RuntimeException("original object cannot be empty"); } if(afterObj == null) { throw new RuntimeException("new object cannot be empty"); } if(! beforeObj.getClass().isAssignableFrom(afterObj.getClass())){ throw new RuntimeException("Two objects are different, cannot be compared"); } //remove attributes Field[] beforeFields = beforeObj.getClass().getDeclaredFields(); Field[] afterFields = afterObj.getClass().getDeclaredFields(); Field.setAccessible(beforeFields, true); Field.setAccessible(afterFields, true); //Traverse to extract difference values if(beforeFields != null && beforeFields.length > 0){ for(int i=0; i