Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing POJO classes  RSS feed

 
Wagner Danda Da Silva Filho
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there!

I need to compare two POJO classes and find out which properties are different. I've tried BeanComparator (from BeanUtils) but it doesn't shows me the different properties...

For example, I have the following class:



And now I have two instances with different values, and I want to compare them:


Now imagine that my POJO classe have lot's of properties, I don't want to add a "if" for each property... Is there an API that could do this dirty work?

PS: I've considered creating my own utility class using reflection, but first I'm searching for a ready solution. I don't like to reinvent the wheel.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at Jakarta Commons BeanUtils, which has a method to return a bean's properties as a Map. You can then iterate through the elements, comparing as needed.

Out of curiosity, I'm assuming you're wanting to compare fields on an individual basis, and not simply comparing objects (in which case you'd look to override equals/hashCode and/or implement Comparable).

Hope this helps...
 
Wagner Danda Da Silva Filho
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Steve, thanks for you help, your assumption is correct.

So, now I'm using "BeanUtils.describe(...)" to get the properties of my POJO as a map. Then I iterate over it and compare the properties of the two POJO classes using "PropertyUtils.getProperty(...)". Here is code I wrote and its working:



Thanks again for your help Steve.
[ November 17, 2005: Message edited by: Wagner Danda ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!