Compare two generic java complex objects

My requirement is to compare two objects of the same unknown / generic type. Objects are complex. They can contain lists, which themselves can contain lists.

So my initial thoughts are to use a comparator to compare objects, reflection to discover all properties of a bean, and some recursion to handle any nested lists of objects it may contain.

or, is there a utility that will do all this for me, in java?

+1


source to share


6 answers


I am currently working on a similar issue. I can confirm that with java reflection you can compare two objects of the same unknown / generic type. I found everything I need to get here . Below is a short description of how to do this:

  • Get two objects in a function
  • Define all ob1 fields
  • Assuming the objects are of the same type, you can use one field to get the value from both objects and compare, for example field.get(ob1).equals(field.get(ob2)



However, comparing objects within objects is much more difficult. I didn't find a solution for it and here's the problem: you need two objects to compare against elements using reflection. I have not yet found a way to extract an object from an object of unknown type. Let me know if you find anything.

0


source


You can use Bean Utilities or use directly ... Apache Commons EqualsBuilder

similar solution



EDITED: Please see this post . After googling, I also found this BeanDiff api that you might find useful.

+1


source


If you can guarantee that the entire nested object tree implements Comparable, you can use:

 public int compareTo(Object o) {
   return CompareToBuilder.reflectionCompare(this, o);
 }

      

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/CompareToBuilder.html

+1


source


I would do it as you mentioned.

  • Make sure both objects are of the same type and
  • Iterating over all variables of object 1
    • Get the value of a variable in object 2
    • Call the valueOfVariableInObject1.compareTo (valueOfVariableInObject2)
0


source


Eve. I suppose you could use Reflection to get a list of fields and navigate from there. You will need complex code to determine if a given field is a simple or complex type, and dig into complex ones when you compare fields.

See this to get started with getting a list of fields, their names and their types.

0


source


Disclaimer: I am not a JAVA developer.

I don't think there is a clean way to compare unknown types. Here's what I would like to do: declare an interface, call it ComparableInterface

interface ComparableInterface {
    function isEqual(ComparableInterface $a);
}

      

Make all classes your unknown object can be instantiated to implement this interface. Then use it for comparison.

Any other solutions I can think of would be an ugly hack: /. Also I think that if you need to compare thinkg that you don't know, you have a problem in your design.

0


source







All Articles