Is there a Java library that can “diff” two Objects?

前端 未结 7 1056
长发绾君心
长发绾君心 2020-11-28 03:35

Is there a Java utility library that is analogous to the Unix program diff, but for Objects? I\'m looking for something that can compare two objects of the same type and ge

7条回答
  •  佛祖请我去吃肉
    2020-11-28 04:12

    Might be a little late, but I was in the same situation like you and ended up creating my own library for exactly your use-case. Since I was forced to come up with a solution myself, I decided to release it on Github, to spare others the hard work. You can find it here: https://github.com/SQiShER/java-object-diff

    --- Edit ---

    Here is a little usage example based on the OPs code:

    SomeClass a = new SomeClass();
    SomeClass b = new SomeClass();
    
    a.setProp1("A");
    a.setProp2("X");
    
    b.setProp1("B");
    b.setProp2("X");
    
    DiffNode diff = ObjectDifferBuilder.buildDefault().compare(a, b);
    
    assert diff.hasChanges();
    assert diff.childCount() == 1;
    assert diff.getChild('prop1').getState() == DiffNode.State.CHANGED;
    

提交回复
热议问题