How can I compare POJOs by their fields reflectively

Since this would probably be implemented using reflection "reflection equals" is a reasonable search term, and indeed Google finds:

http://www.unitils.org/tutorial-reflectionassert.html


Override the toString() method in your pojo class like below

@Override
public String toString() {
    return "brand: " + this.brand + ",color: " + this.color;
}


car1.toString().equals(car2.toString()); //It will return true if both objects has same values

In case you have large nos of parameter i will suggest you to go with bellow code

public static boolean comparePOJO(Object obj1, Object obj2) {
    return new Gson().toJson(obj1).equals(new Gson().toJson(obj2));
}
comparePOJO(car1,car2); //It will return true

This type of reflection is built into Hamcrest as SamePropertyValuesAs, which compares bean-named properties (getFoo, isBar) instead of the fields that likely power them. Core Hamcrest support is built into JUnit, so you'd just need to add the Hamcrest library that includes the SamePropertyValuesAs matcher.

assertThat(car1, samePropertyValuesAs(car2));

Unitils seems to do solve the purpose for me. The following APIs can compare objects reflectively. It can compare even if the attributes of a POJO themselves are user defined POJOs :

import static org.unitils.reflectionassert.ReflectionAssert.*;

// Exact field-by-field comparison
assertReflectionEquals(new Person("John", "Doe", new Address("New street", 5, "Brussels")), 
                                 new Person("John", "Doe", new Address("New street", 5, "Brussels"));

// Ignore Null / 0 values in the expected object
assertReflectionEquals(new Person("John", null, new Address("New street", 0, null)),
                                 new Person("John", "Doe", new Address("New street", 5, "Brussels"), 
                                 ReflectionComparatorMode.IGNORE_DEFAULTS); 

// Ignore collection order
assertReflectionEquals(Arrays.asList(new Person("John"), new Person("Jane")),
                                 new Person[] {new Person("Jane"), new Person("John")}, 
                                 ReflectionComparatorMode.LENIENT_ORDER);

// Ignore null/0 values + collection order
assertLenientEquals(Arrays.asList(new Person("John"), null),
                                 new Person[] {new Person("Jane", "Doe"), new Person("John", "Doe")});

// Check only the firstName property 
assertPropertyLenientEquals("firstName", Arrays.asList("John", "Jane"),
                                 new Person[] {new Person("Jane", "Doe"), new Person("John", "Doe")});

Further information at Unitils Cookbook