Deep Comparision of Two Java Objects

2019-06-11 13:09发布

Already referred few question here and there.

Use Case -

1.) Given any Two objects, compare both of them property by property.

2.) It will contains Collections also, now compare collections of both the objects, now inside collection same data can be upside down, meaning say i have List<Address>, it contains two entries in both (say Residential Address, Office Address), but in both list the data may be at different indexes.

3.) Need to create 3rd Object of same type, with similar data copied, and properties set to null with different data.

4.) It might have reference classes as well.

I tired many solutions but stuck somewhere or the other, i am thinking of writing some generic solution. Though of generating two xml's out of the two objects and then comparing node by node, but just want to get more options.

Or How much Java reflection is stronger in this case.

1条回答
等我变得足够好
2楼-- · 2019-06-11 13:56

answer to @markspace question.

To access a private field you will need to call the Class.getDeclaredField(String name) or Class.getDeclaredFields() method. The methods Class.getField(String name) and Class.getFields() methods only return public fields, so they won't work.

To access a private method you will need to call the Class.getDeclaredMethod(String name, Class[] parameterTypes) or Class.getDeclaredMethods() method. The methods Class.getMethod(String name, Class[] parameterTypes) and Class.getMethods() methods only return public methods.

XMLUnit will work, it compares the list references recursively, also it has option to exclude fields which you do not wish 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 pieces of XML. Allows elements of complex, deeply nested types that are returned in different orders but have the same content to be recognized as comparable.

查看更多
登录 后发表回答