Deep comparison of two Java objects

Several questions have already been mentioned here and there .

Use case -

1.) For any Two objects

, compare

both properties by property.

2.) It also contains Collections

now compares the collection of two objects, now in the collection of the same data can be inverted, which means that I have List<Address>

, it contains two records in both (for example Residential Address

, Office Address

), but in both lists, data may have different indices.

3.) It is necessary to create 3rd Object

the same type, with similar data copied and properties equal to zero, with different data.

4.) It can also have referenced classes.

I'm tired of many solutions but stuck somewhere, I'm thinking of writing some general solution. Although generating two xml's

from two objects and then comparing node to node, but just want more options.

Or How much is Java reflection

stronger in this case.

0


source to share


1 answer


answer @markspace's question.

To access private field

you need to call the method Class.getDeclaredField(String name)

or Class.getDeclaredFields()

. Methods Class.getField(String name)

and Class.getFields()

only return public fields

, so they won't work.

To access private method

you need to call the method Class.getDeclaredMethod(String name, Class[] parameterTypes)

or Class.getDeclaredMethods()

. Methods Class.getMethod(String name, Class[] parameterTypes)

and Class.getMethods()

nothing more return public methods

.

XMLUnit

will work, it compares the list references recursively, also has the ability to exclude fields you don't want to compare.



 String expectedXML = "some xml";
 String actualXML = "some xml";

 DetailedDiff diff1 = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
 diff1.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
 System.out.println("Differences found: " + diff1.getAllDifferences().toString());

      

RecursiveElementNameAndTextQualifier

Compares all Element and Text nodes in two XML parts. Allows items of complex, deeply nested types to be returned on different orders, but with the same content that is comparable.

0


source







All Articles