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

前端 未结 7 1049
长发绾君心
长发绾君心 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 03:56

    http://javers.org is library that does exacly what you need: has methods like compare(Object leftGraph, Object rightGraph) returning the Diff object. Diff contains a list of changes (ReferenceChange, ValueChange, PropertyChange) e.g.

    given:
    DummyUser user =  dummyUser("id").withSex(FEMALE).build();
    DummyUser user2 = dummyUser("id").withSex(MALE).build();
    Javers javers = JaversTestBuilder.newInstance()
    
    when:
    Diff diff = javers.compare(user, user2)
    
    then:
    diff.changes.size() == 1
    ValueChange change = diff.changes[0]
    change.leftValue == FEMALE
    change.rightValue == MALE
    

    It can handle cycles in graphs.

    In addition you can get Snapshot of any graph object. Javers has JSON serializers and deserializers to snapshot, and changes so you can easily save them in database. With this library you can easily implement a module for auditing.

提交回复
热议问题