java object diff,是否存在可以“差异”的Java库?两个对象?

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 generate a data structure that represents the differences between them (and can recursively compare differences in instance variables). I'm not looking for a Java implementation of a text diff. I'm also not looking for help with how to use reflection to do this.

The application I'm maintaining has a fragile implementation of this functionality that had some poor design choices and that needs to be rewritten, but it would be even better if we could use something off the shelf.

Here's an example of the kind of thing I'm looking for:

SomeClass a = new SomeClass();

SomeClass b = new SomeClass();

a.setProp1("A");

a.setProp2("X");

b.setProp1("B");

b.setProp2("X");

DiffDataStructure diff = OffTheShelfUtility.diff(a, b); // magical recursive comparison happens here

After comparison, the utility would tell me that "prop1" is different between the two objects and "prop2" is the same. I think it's most natural for DiffDataStructure to be a tree, but I'm not going to be picky if the code is reliable.

解决方案

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值