• Post Reply Bookmark Topic Watch Topic
  • New Topic

howto Log it? Looking for a generic method that checks objects fields (compare 2 obj)  RSS feed

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

I'm trying to build a logging mechanism that logs only the revisions made on an object (find the difference in the fields. think of an object that the user just got from the db, now he makes revisions - I wish to find those revisions)

I wonder if anyone knows any *generic* method that loops through 2 instances of the same class and find the difference in terms of their fields. In other words loop through 2 object's fields and compare them (must be the same class).

Below is a code example.
thanks for any thoughts.



 
Jeff Rummings
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I wonder if anyone knows any *generic* method that loops through 2 instances of the same class and find the difference in terms of their fields.


What would such a method return? The diff(...) method in your example is void. You could have an equals method that uses reflection (I think EqualsBuilder from Jakarta commmons does something like that).
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Peter:I wonder if anyone knows any *generic* method that loops through 2 instances of the same class and find the difference in terms of their fields. In other words loop through 2 object's fields and compare them


Have you tried anything using reflection?
If you are comparing based on public fields/getters(java bean convention), then this must be straight forward.
All you have to do is list the getters, execute them for both the instances. Compare the values using equals. If not equal then the field has changed.
The trick is that if the field is an object other than the primitive type then you must call the diff generator recursively.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!