My thoughts on the equals method (Java)

I made it because I wanted to compare beans with JUnit.

/**
 *Convenient equals method
 *OK even if the equals method is not implemented.I'll also check the superclass fields.
 * @param a
 * @param b
 * @return
 */
@SuppressWarnings("unchecked")
public static boolean reflectEquals( Object a, Object b ){
        try{
        if (a == b) {
            return true;
        }
        if (a == null || b == null ) {
            return a == b;
        }
        if (a.getClass() != b.getClass()) {
            return false;
        }
        boolean useBuildinEqualsFlg = a.getClass().getName().startsWith("java.lang");
        if( useBuildinEqualsFlg ){
            try{
                Method equalsMethod = a.getClass().getDeclaredMethod("equals", Object.class);
                boolean eqFlg = Boolean.class.cast( equalsMethod.invoke(a, b) );
                return eqFlg;
            }catch( NoSuchMethodException e ) {
                String aStr = a.toString();
                String bStr = b.toString();
                boolean eqFlg = aStr.equals(bStr);
                return eqFlg;
            }
        }else{
            if( a instanceof List ) {
                a = ((List<Object>) a).toArray();
                b = ((List<Object>) b).toArray();
            }
            if( a.getClass().isArray() ) {
                int aLen = Array.getLength(a);
                int bLen = Array.getLength(b);
                if( aLen != bLen ) {
                    return false;
                }
                for( int i = 0;i<aLen;i++) {
                    Object aElement= Array.get(a, i);
                    Object bElement= Array.get(b, i);
                    if( !reflectEquals( aElement, bElement ) ) {
                        return false;
                    }
                }
                return true;
            }
            List<Field> fields = getAllFields(a.getClass());
            for( Field field : fields ) {
                field.setAccessible(true);
                Object aFieldObj = field.get(a);
                Object bFieldObj = field.get(b);
                boolean eqFlg = reflectEquals( aFieldObj, bFieldObj);
                if( !eqFlg ) {
                    return false;
                }
            }
            return true;
        }
    }catch(IllegalAccessException | IllegalArgumentException | SecurityException | InvocationTargetException e ){
        throw new RuntimeException(e);
    }
}

/**
 *Superclass also goes back and gets all fields
 * @param clazz
 * @return
 */
private static List<Field> getAllFields(Class<?> clazz){
	List<Field> allFields = new ArrayList<>();
	if( clazz != Object.class ) {
		Field[] fields = clazz.getDeclaredFields();
		allFields.addAll( Arrays.asList(fields) );
		allFields.addAll( getAllFields(clazz.getSuperclass()) );
	}
	return allFields;
}

↓ Call like this.

reflectEquals(obj1, obj2)

After making a masterpiece, I realized that this is all I need to do ...

Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.toJson(obj1).equals( gson.toJson(obj2) );

Recommended Posts

My thoughts on the equals method (Java)
My thoughts on the future [Preparation]
My thoughts on the future [Gradle app version ①]
[Java Silver] About equals method
My thoughts on Othello [Thinking Routine 2]
Java comparison using the compareTo () method
[Java beginner] == operator and equals method
Consideration on the 2017 Java Persistence Framework (1)
My thoughts on Othello [Thinking Routine 1]
Call the super method in Java
Java method
java (method)
Java method
[Java] method
[Java] method
[Java] How to compare with equals method
Kick ShellScript on the server from Java
Install OpenJDK (Java) on the latest Ubuntu
[Java] How to use the toString () method
What is the main method in Java?
Looking back on the basics of Java
Execute Java code stored on the clipboard.
Deepened my understanding of the merge method
Thoughts on Java Interviews you never Knew
[Java] Handling of JavaBeans in the method chain
I tried putting Java on my Mac easily
Come out with a suffix on the method
The order of Java method modifiers is fixed
My DOM (Java)
Java8 method reference
About the method
[Java] forEach method
Come out with a suffix on the method 2
How to use the replace () method (Java Silver)
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
Compile and run Java on the command line
My StAX (Java)
I touched on the new features of Java 15
java8 method reference
[Java] Random method
[Java] Memo on how to write the source
My Java reference
[Java] split method
The comparison of enums is ==, and equals is good [Java]
Deploy Java apps on the IBM Cloud Kubernetes service
Output about the method # 2
Let's touch on Java
My DAO pattern (Java)
JAVA DB connection method
Install Java on Mac
Java learning 2 (learning calculation method)
Java learning memo (method)
About Java method binding
Run PostgreSQL on Java
[Java ~ Method ~] Study memo (5)
About method splitting (Java)
Studying Java 8 (see method)
About the length method
Java programming (class method)
My Study Note (Java)
About the authenticate method.