0

I recently debated with a collegue about how to compare 2 instances of the same java class.

You have an two instances of a complicated object and want to know which attributes differ between those two.

Here is a use case : You have a user profile with lot of fields and the user submits a new profile, you want to know which fields have changed to be able to display something like "successfully changed your birthday, name, street name ..."

So at the moment, the best solution I have is to write a compare method in the class that takes another object and compare every field one by one, then return the list of fields that are differents.

I was wondering if there was any automatic method (from a external library for example) to do that without having to manually specify each attribute.

Btw, if hibernate has a method which could do this to compare local and database object it could do the trick.

Estragon
  • 1,462
  • 11
  • 12
  • Hope this helps, similar thread - http://stackoverflow.com/questions/369512/best-way-to-compare-objects-by-multiple-fields – Karthik Ananth Apr 24 '12 at 09:59
  • 1
    You could probably use reflection for that purpose (using `getClass().getDeclaredFields()`) or something of that taste. But I would guess that somebody has already written and published such code, so maybe someone knows about this. – Guillaume Polet Apr 24 '12 at 10:02

1 Answers1

2

Use reflection, as noted by Guillaume Polet. I'd also put an annotation on the fields that need to be exposed like this. If you don't like the idea of public fields, use getX() methods with annotations. I don't know of any library code to do the comparison; but it wouldn't take long to write.

Theodore Norvell
  • 15,366
  • 6
  • 31
  • 45