sort fields in HashCodeBuilder for deterministic order (#480)

This commit is contained in:
contextshuffling 2019-11-22 11:15:10 -06:00 committed by Gary Gregory
parent 1163e17713
commit bc8a3b9d84
2 changed files with 7 additions and 4 deletions

View File

@ -20,7 +20,9 @@ package org.apache.commons.lang3.builder;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
@ -189,6 +191,7 @@ public class HashCodeBuilder implements Builder<Integer> {
try {
register(object);
final Field[] fields = clazz.getDeclaredFields();
Arrays.sort(fields, Comparator.comparing(Field::getName));
AccessibleObject.setAccessible(fields, true);
for (final Field field : fields) {
if (!ArrayUtils.contains(excludeFields, field.getName())

View File

@ -490,11 +490,11 @@ public class HashCodeBuilderTest {
public void testReflectionHashCodeExcludeFields() {
final TestObjectWithMultipleFields x = new TestObjectWithMultipleFields(1, 2, 3);
assertEquals(((17 * 37 + 1) * 37 + 2) * 37 + 3, HashCodeBuilder.reflectionHashCode(x));
assertEquals(((17 * 37 + 1) * 37 + 3) * 37 + 2, HashCodeBuilder.reflectionHashCode(x));
assertEquals(((17 * 37 + 1) * 37 + 2) * 37 + 3, HashCodeBuilder.reflectionHashCode(x, (String[]) null));
assertEquals(((17 * 37 + 1) * 37 + 2) * 37 + 3, HashCodeBuilder.reflectionHashCode(x));
assertEquals(((17 * 37 + 1) * 37 + 2) * 37 + 3, HashCodeBuilder.reflectionHashCode(x, "xxx"));
assertEquals(((17 * 37 + 1) * 37 + 3) * 37 + 2, HashCodeBuilder.reflectionHashCode(x, (String[]) null));
assertEquals(((17 * 37 + 1) * 37 + 3) * 37 + 2, HashCodeBuilder.reflectionHashCode(x));
assertEquals(((17 * 37 + 1) * 37 + 3) * 37 + 2, HashCodeBuilder.reflectionHashCode(x, "xxx"));
assertEquals((17 * 37 + 1) * 37 + 3, HashCodeBuilder.reflectionHashCode(x, "two"));
assertEquals((17 * 37 + 1) * 37 + 2, HashCodeBuilder.reflectionHashCode(x, "three"));