Your question is a bit unclear. First you said “two instances of the same class”, then you said “classes are very complex”. Is this a general solution for finding differences between instances for any class, or is it just a specific case? Another ambiguity is what you mean by "copy of differences." For example, if it is a row, then what is the difference between the two rows that will be copied to a new instance? If it's a collection, what's the difference between collections? What if you have two ArrayLists that have the same things in different orders.
If this is a specific case, you can simply create a method in a class in which you pass an instance of the same class. You can then iterate over each field and compare the differences.
public TheClass difference(TheClass that) { TheClass newClass = new TheClas() if (this.getName().equals(that.getName()) == false ) { newClass.setName(that.getName()); } ... }
But this can get out of control depending on how deep your graph is.
Perhaps the linker template might come in handy here if you are trying to create a one-stop / reusable solution. You can look at the Apache Commons code base and see how they implement HashCodeBuilder and ToStringBuilder. They even have a mirrored version of the utility. See how they deal with deep and shallow peers.
Javid jamae
source share