sort fields in HashCodeBuilder for deterministic order (#480)
This commit is contained in:
parent
1163e17713
commit
bc8a3b9d84
|
@ -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())
|
||||
|
|
|
@ -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"));
|
||||
|
|
Loading…
Reference in New Issue