General reflexive helper method for equals and hashCode

I am going to create a reflective helper method for equals and hashCode.

  • In case of equality, the helper method looks through the reflection API for the fields of object A and compares them with the fields of object B.
  • In the case of hashCode, the helper method looks up the reflection API for the fields and computes the hashCode in the iteration loop.

Good thing I should not worry about missing fields in my equals or hashCode implementation. Bad, I think, performance. What do you think of this idea? Please share your opinion!

This is my first draft for peers:

public final class ReflectiveEqualsHelper {

public static boolean isEqual(final Object a, final Object b) {
    if (!isTypeEqual(a, b)) {
        return false;
    }

    Field[] fields = getFields(a);

    Object valueA;
    Object valueB;
    String fieldName;
    for (int i = 0; i < fields.length; i++) {
        fieldName = fields[i].getName();
        valueA = getValueByFieldName(a, fieldName);
        valueB = getValueByFieldName(b, fieldName);
        if (!compare(valueA, valueB)) {
            return false;
        }
    }
    return true;
}

@SuppressWarnings("rawtypes")
private static Field[] getFields(final Object o) {
    Class clazz = o.getClass();
    Field[] fields = clazz.getDeclaredFields();
    return fields;
}

private static Field getField(final Object o, final String name) {
    try {
        Field field = o.getClass().getDeclaredField(name);
        return field;
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
}

private static Object getValueByFieldName(final Object o, final String name) {
    Field field = getField(o, name);
    field.setAccessible(true);

    try {
        Object value = field.get(o);
        field.setAccessible(false);
        return value;
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

}

private static boolean areBothNull(final Object a, final Object b) {
    return (a == null && b == null);
}

private static boolean isTypeEqual(final Object a, final Object b) {
    if (areBothNull(a, b)) {
        return false;
    }

    return a.getClass().equals(b.getClass());
}

private static boolean compare(final Object a, final Object b) {
    if (a == null) {
        return false;
    } else if (b == null) {
        return false;
    }
    return a.equals(b);
}

}

public class ReflectiveEqualsHelperTest {

@Test
public void testIsEqual() {
    Vector a = new Vector(Long.valueOf(1L), 3L);
    Vector b = new Vector(Long.valueOf(1L), 3L);
    Vector c = new Vector(Long.valueOf(2L), 3L);
    boolean testA = ReflectiveEqualsHelper.isEqual(a, b);
    boolean testB = ReflectiveEqualsHelper.isEqual(a, c);
    boolean testC = ReflectiveEqualsHelper.isEqual(b, c);
    assertTrue(testA);
    assertFalse(testB);
    assertFalse(testC);
}

class Vector {
    public static final int STATIC = 1;

    private Long x;
    private long y;

    public Vector(Long x, long y) {
        super();
        this.x = x;
        this.y = y;
    }

    public Long getX() {
        return x;
    }

    public void setX(Long x) {
        this.x = x;
    }

    public long getY() {
        return y;
    }

    public void setY(long y) {
        this.y = y;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        result = prime * result + (int) (y ^ (y >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        return ReflectiveEqualsHelper.isEqual(this, obj);
    }
}

}

Cheers, Kevin

+3
source share
5 answers
+4

Guava Objects.hashCode. :

public int hashCode() {
     return Objects.hashCode(getX(), getY(), getZ());
}

Objects.equals isEquals.

+3

. , . . IDE, ​​ Eclipse, IntelliJ Netbeans, equals() hashCode(). , Eclipse rightclick - > Source > Generate hashCode .

alt text

+2

, , - , .

. , .

+2

- . EqualsBuilder HashCodeBuilder Apache ( ), . #equals #hashCode Fast Code Eclipse :


<template type="EQUALS_AND_HASHCODE_METHOD">
  <variation></variation>
  <variation-field></variation-field>
  <allow-multiple-variation></allow-multiple-variation>
  <class-pattern></class-pattern>
  <allowed-file-extensions>java</allowed-file-extensions>
  <number-required-classes>1</number-required-classes>
  <description>Generates the equals and hashCode method with EqualsBuilder and HashCodeBuilder</description>
  <template-body>
    <![CDATA[
      @Override
      public boolean equals(final Object obj) {
        if (obj == null) {
          return false;
        }
        if (obj == this) {
          return true;
        }
        if (obj.getClass() != getClass()) {
          return false;
        }

        ${class_name} rhs = (${class_name}) obj;
        return new EqualsBuilder().appendSuper(super.equals(obj))
        #foreach ($field in ${fields})
          .append(${field.name}, rhs.${field.name})
        #end
          .isEquals();
      }

      @Override
      public int hashCode() {
        return new HashCodeBuilder(17, 37).appendSuper(super.hashCode())
        #foreach ($field in ${fields})
          .append(${field.name})
        #end
          .toHashCode();
      }
    ]]>
  </template-body>
</template>

I use the Fast Code plugin because it is able to capture all the fields of the selected class. But I am not satisfied with the convenience of the plugin. It would be nice if the Eclipse template modeling engine could do this. If someone knows a similar plugin, then let me know, please!

Cheers, Kevin

+1
source

Source: https://habr.com/ru/post/1779745/


All Articles