Deep Comparision of Two Java Objects

南笙酒味 提交于 2019-12-10 12:04:58

问题


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:


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.



来源:https://stackoverflow.com/questions/26877777/deep-comparision-of-two-java-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!