2

Is there a way in which we can equate two objects?

I know that we can use equals, but the problem is that I need to write a utility which can compare any two objects implementing same interface.

Now the object can have 1 attribute, or 2 attribute or can have 100 attribute. and i need to compare each and every attribute to prove then exactly equal.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
M.J.
  • 16,266
  • 28
  • 75
  • 97
  • You can try and use reflection to iterate the two objects attributes and compare them. (it is implied in your question that you don't to implement equals or a comparator...) – Ido.Co Feb 29 '12 at 12:00
  • @Ido. CO : can you please give an example how to do the same. I Know how to use reflection, but not sure exactly how to do that. – M.J. Feb 29 '12 at 12:08
  • I'll look for a good example for you. – Ido.Co Feb 29 '12 at 12:23

3 Answers3

2

You may have a look at the Apache Commons helper classes EqualsBuilder and HashCodeBuilder. These classes provides methods to build good equals and hashCode method for any class.

Keshaw Kumar
  • 317
  • 1
  • 4
  • 15
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73
0

This can be done using reflection. If you don't want to write your own utility, you can use something like Unitils, which provides a class called ReflectionAssert.

See also Is there a Java reflection utility to do a deep comparison of two objects?

Community
  • 1
  • 1
nwinkler
  • 52,665
  • 21
  • 154
  • 168
0

If you don't want to implement equals or a comparator, you can try and do it by reflection.

Iterate over the two objects fields and compare them -

Field[] fields1 = o1.getClass().getDeclaredFields();
Field[] fields2 = o2.getClass().getDeclaredFields();

for (int i = 0; i++ ; i>fields.lenght) {
 // compare the two fields under the assumption that if the two
 // objects are the same their fields will be the same in each iteration
}

use field.get(Object) to retrieve the value of the field

Since there might be nesting and collections of object involved, you'll have to do it recursively for each element, and pointer cycles might present a problem. so if you're expecting cycles you'll have to implement more complex solution (you'll have to store the actual pointers. and check that you are not trying to recursively compare the same elements twice).

Ido.Co
  • 5,317
  • 6
  • 39
  • 64
  • It's not that easy. How do you handle nested collections? How do you make sure you're not ending in a cycle? Implementing this is not trivial... – nwinkler Feb 29 '12 at 13:20
  • About comparing collections- this comparison should be done recursively for every element (or use it's implementation of equals instead). About cycles - This is a problem. you shouldn't you use this method if you expect cycles (although there is a solution: addresses memoization, but it's ugly) – Ido.Co Feb 29 '12 at 13:37