Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object diff utility [duplicate]

Tags:

java

diff

I am looking for a generic utility in Java, that can help me create a diff report for two objects (of the same type).

For instance, if my class structure is:

class A {
  int p1;
  string p2;
  B b1;
}

class B {
 float p3;
}

I want a report b/w two objects of type A (say, a1 and a2), as follows: a1 vs. a2

p1 : 'remove'
p2 : 'change'
b1.p3: 'add'

wherein, 'remove' is set if the property was null in the second object, 'change' if the properties were present but had different values, and 'add' if the property was null in the first object.

It may get tougher/trickier for collection objects...

like image 558
Saket Avatar asked Nov 30 '22 05:11

Saket


1 Answers

I created a library for that: https://github.com/SQiShER/java-object-diff

It builds a tree structure of your compared objects and allows you to traverse the nodes via visitor pattern. Take a look at the Getting Started page, to see some examples. It works with almost any kind of object and can handle as many nesting levels as you like. I even managed to build an automatic object merger based on it.

A printed version of such an object graph looks like this:

Property at path '/contacts/item[Walter White]/middleName' has been added => [ Hartwell ]
Property at path '/contacts/item[Jesse Pinkman]/middleName' has been added => [ Bruce ]

I'm using it myself and it works like a charm. Hope it helps!

I don't know how complex your objects are, but doing it manually via reflection gets out of hand rather quickly. Especially when Maps and Collections get involved.

like image 167
SQiShER Avatar answered Dec 02 '22 20:12

SQiShER