java-object-diff 是一个简单但功能强大的寻找Java对象之间的差异的库。这需要对比两个对象,并能生成一个树状结构表示对象和他们的子对象之间的差异。然后,这个树状结构可以通过提取更多信息或更改应用到底层的数据结构。
Using with Maven
<dependency>
<groupId>de.danielbechler</groupId>
<artifactId>java-object-diff</artifactId>
<version>0.95</version>
</dependency>
Using with Gradle
compile 'de.danielbechler:java-object-diff:0.95'
public class JavaObjectDiff {
public static void main(String[] args) {
Map<String, String> working = Collections.singletonMap("item", "foo");
Map<String, String> base = Collections.singletonMap("item", "bar");
DiffNode diff = ObjectDifferBuilder.buildDefault().compare(working, base);
System.out.println(diff.hasChanges());
System.out.println(diff.childCount() == 1);
NodePath itemPath = NodePath.startBuilding().mapKey("item").build();
System.out.println(diff.getChild(itemPath).getState() == DiffNode.State.CHANGED);
/**
* method1 Traversal
*/
diff.visit(new DiffNode.Visitor() {
@Override
public void node(DiffNode node, Visit visit)
{
System.out.println(node.getPath() + " => " + node.getState());
}
});
/**
* method2 Reading Values
*/
diff.visit(new DiffNode.Visitor() {
@Override
public void node(DiffNode node, Visit visit)
{
final Object baseValue = node.canonicalGet(base);
final Object workingValue = node.canonicalGet(working);
final String message = node.getPath() + " changed from " +
baseValue + " to " + workingValue;
System.out.println(message);
}
});
}
输出结果
true
true
true
/ => CHANGED
/{item} => CHANGED
/ changed from {item=bar} to {item=foo}
/{item} changed from bar to foo
根据被比较对象的内部各层类型的equals方法进行比较,所以可以通过override来定义比较规则!
官网:java-object-diff
Github: Github