Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two objects with Groovy

Tags:

groovy

Is there an easy utility with Groovy that will give me a difference of two different objects? I'm getting the message via the equals method that they aren't equal but where can I find what properties are not being matched?

like image 309
monksy Avatar asked Dec 05 '14 22:12

monksy


People also ask

Can you use == to compare objects?

The == operator compares whether two object references point to the same object. For example: System.

How do you compare values in two objects?

Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.

What does == mean in groovy?

Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.

Why use .equals instead of == Java?

The == operator can't compare conflicting objects, so at that time the compiler surrenders the compile-time error. The equals() method can compare conflicting objects utilizing the equals() method and returns “false”.


1 Answers

I found that this was easy to do as that the .properties attribute of the object produced a map listing the property name as the key and the value as the value.

Once I had that then I could do a difference between the two maps and I've got the answer I was looking for.

Each of the objects has a .properties extension. This works like the Python .dict.

Example

object1.properties - object2.properties

So these will show you the difference between the object1 properties and object2 properties, but only where there exist an entity (key+value) that differs from within object2. If there are extra properties in object2 they will not be shown.

like image 66
monksy Avatar answered Sep 21 '22 06:09

monksy