java-object-diff icon indicating copy to clipboard operation
java-object-diff copied to clipboard

Comparing objects?

Open cmadsen opened this issue 8 years ago • 3 comments

Why is does (using java-object-diff:0.94)

DiffNode diff = ObjectDifferBuilder.buildDefault().compare(
			new Person(1, "Bob", "London"),
			new Person(2, "Peter", "Paris"));

result in diff.hasChanges()==false?

import static java.lang.System.*;
import static org.assertj.core.api.Assertions.*;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.junit.Test;

import de.danielbechler.diff.ObjectDifferBuilder;
import de.danielbechler.diff.node.DiffNode;

public class Compare {
	static public class Person {
		int id;
		String name;
		String city;

		public Person() {
		}

		Person(int id, String name, String city) {
			this.id = id;
			this.name = name;
			this.city = city;
		}

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof Person)) {
				return false;
			}
			if (this == obj) {
				return true;
			}
			final Person otherObject = (Person) obj;
			return new EqualsBuilder().append(this.id, otherObject.id)
					.isEquals();
		}

		@Override
		public int hashCode() {
			return new HashCodeBuilder().append(id).toHashCode();
		}
	}

	@Test
	public void compareMaps() {
		DiffNode diff = ObjectDifferBuilder.buildDefault().compare(
				new Person(1, "Bob", "London"),
				new Person(2, "Peter", "Paris"));
		assertThat(diff.hasChanges()).isTrue();
	}
}

cmadsen avatar Feb 03 '17 09:02 cmadsen

ha! i ran into this same pretty quick after using this. you're missing getters. i really wish you didn't have to provide them as i'm using this lib mostly with my DTOs that are SUPER simple and didn't have getters/setters.

denov avatar Feb 10 '17 22:02 denov

That's why I use lombok, I really dislike all that boilerplate code needed.

olasundell avatar Feb 13 '17 09:02 olasundell

In this case I'm sure you guys will be happy about PR https://github.com/SQiShER/java-object-diff/pull/182, which aims to replace the current Introspector with a version that can deal with simple fields. The PR is more or less feature-complete but requires some more testing to make sure it doesn't break anything when it becomes the new default. Feedback is welcome.

SQiShER avatar Feb 13 '17 23:02 SQiShER