Skip to content

Commit

Permalink
#143. Better makeThemEquals implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Piotr Joński committed Nov 23, 2016
1 parent 13068a8 commit c9aa11f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,21 @@ private Map<Class<?>, Predicate<String>> convertToMap(final ClassAndFieldPredica
}

private Object makeThemEqual(final Object object, final Object newInstance) {
final List<Field> allFields = FieldUtils.getAllFields(object.getClass());
final List<Field> allFields = getAllFields(object);
for (final Field field : allFields) {
final Object value = FieldUtils.getValue(object, field);
FieldUtils.setValue(newInstance, field, value);
}
return newInstance;
}

private List<Field> getAllFields(final Object object) {
Class<?> parent = object.getClass();
final List<Field> allFields = new ArrayList<>();
do {
allFields.addAll(FieldUtils.getAllFields(parent));
} while ((parent = parent.getSuperclass()) != null);
return allFields;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
import classesForTest.fields.collections.map.Maps;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.lang3.builder.EqualsBuilder;
Expand All @@ -27,6 +31,7 @@

import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Stream;

import static helpers.TestHelper.getDefaultDisplayName;
Expand Down Expand Up @@ -73,7 +78,8 @@ public Stream<DynamicTest> Should_Create_Same_Instance() {
return Stream.of(new GoodPojo_Equals_HashCode_ToString(),
new ObjectContainingArray(),
new Collections(),
new Maps())
new Maps(),
new SecondChild())
.map(value -> dynamicTest(getDefaultDisplayName(value), Should_Create_Same_Instance(value)));
}

Expand Down Expand Up @@ -502,5 +508,31 @@ public void setTestEnum1(final TestEnum1 testEnum1) {
}
}

@Data
private class Parent {
private final UUID parentUUID;

private Parent() {this.parentUUID = UUID.randomUUID();}
}

@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
private class FirstChild extends Parent {
private final UUID childUUID;

private FirstChild() {this.childUUID = UUID.randomUUID();}
}

@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
private class SecondChild extends FirstChild {
private final UUID secondChild;

private SecondChild() {this.secondChild = UUID.randomUUID();}
}

}

0 comments on commit c9aa11f

Please sign in to comment.