File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Comparing two Java Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing two Java Objects" Watch "Comparing two Java Objects" New topic

Comparing two Java Objects

Ben Zaidi
Ranch Hand

Joined: Apr 08, 2007
Posts: 151
Dear All,

I have a question. I want to compare two java beans of the same type. My problem is this, my bean is having
almost 100 fields, so if i start comparing the properties one by one, it will be hell lot tedious. Like we use BeanUtils.copy()
to copy the properties from one bean to the other, can we compare two beans somewhat?

I don't want to compare the properties one by one. Secondly my java bean is a simple bean, it is not implementing any
comparator interface even.

Any help or pointer in this regard will be highly helpful.


--Lost in preparation of SCJP and SCWCD--
"Start writing a new chapter, for if you live by the book you'll never make history." (Ben Sobel)
Dawn Charangat
Ranch Hand

Joined: Apr 26, 2007
Posts: 249
no need to check each field... just like you have a composite primary key in databases, try identifying a few number of fields which will identify your object as unique... and companre those fields in the equals() method.
Ben Zaidi
Ranch Hand

Joined: Apr 08, 2007
Posts: 151
Actually i am writing a JUnit test case and for this purpose, i need to compare the full result with the desire bean

Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

You can use reflection, but you lose control over the order in which the fields are compared that way.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Comparing two Java Objects
It's not a secret anymore!