2

I need to compare two objects in Java, but they contain a lot of members, some not visible, and I don't have access to the source code - they're objects from a third-party package.

I need to find out what are the differences between them. Something like comparing chunks of memory in C++. But I don't know how to do it in Java.

Any help?

EDIT: Some further info: I am doing some operations on two objects - on one the ops succeed, on the other they fail. However I can't tell what's different, that's why I need this comparison. I can't seem to get reflection to work, member not visible exception or smth like that on private members.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    Do you need that for debugging (i.e. compare them once) or in a piece of logic? – Lukas Eder Oct 27 '11 at 10:01
  • 2
    Doesn't `o1.equals(o2)` work? – rid Oct 27 '11 at 10:03
  • @Radu That would only work if those two objects implement equals with the proper semantics, and if the types of their members do the same. This is like the compare version of a deep clone... You're out of luck if even one member type doesn't bother overriding equals. – G_H Oct 27 '11 at 10:09
  • 1
    @G_H, of course, I'm aware of that, that's why it was a question, not an answer. If the classes are part of quality libraries, they should support `equals()`. – rid Oct 27 '11 at 10:10
  • @Radu Fair enough. But we don't have a lot of background info. Seeing how he mentioned the classes are third-party, it'd be dangerous to rely on this assumption. And some members might be classes from the Java SE API that don't override equals. – G_H Oct 27 '11 at 10:12
  • @Radu i want to compare the members and see what's different, not see if they're equal. – Luchian Grigore Oct 27 '11 at 10:21
  • @Luchian Grigore, ah, I see now what you mean. – rid Oct 27 '11 at 10:25

3 Answers3

2

Take a look at this question Is there a Java reflection utility to do a deep comparison of two objects?

Unitils might help in your case

Community
  • 1
  • 1
denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
1

Reflection is one possible way to do it.

Via Java Reflection, you can gain access to the two objects and their contents, irrespective if it's private or not. Be careful though, this could be seen as reverse engineering and you might be violating your license agreement using reflection.

Ewald
  • 5,691
  • 2
  • 27
  • 31