Jakub is a Java EE developer since 2005 and occasionally a project manager, working currently with Iterate AS. He's highly interested in developer productivity (and tools like Maven and AOP/AspectJ), web frameworks, Java portals, testing and performance and works a lot with IBM technologies. A native to Czech Republic, he lives now in Oslo, Norway. Jakub is a DZone MVB and is not an employee of DZone and has posted 155 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy: Use @Canonical to Get Compiler-generated Equals, HashCode and ToString

11.07.2011
| 3299 views |
  • submit to reddit

Groovy makes it extremely easy to create Java beans with getters, setters, equals, hashCode, and toString:

@groovy.transform.Canonical
class Call {
   def method
   def args

   /* // custom impl. reusing the auto-generated one:
   String toString() {
      _toString().replaceFirst("^.*?Call", "")
   }*/
}

You can then do:

// Auto-gen. constr. with positional arguments:
def call1 = new Call("someMethod", "someArgs")
def call2 = new Call(method: "someMethod", args: "someArgs")
assert call1.getMethod() == call1.method
assert call2.equals(call1)
assert ([call1, call2] as Set).size() == 1 // hashCode

As you might have noticed, you may provide your own implementation of toString and reuse the auto-generated toString by calling _toString().

References

JavaDoc for @Canonical. You can also use separately any of: @ToString. @EqualsAndHashCode, @TupleConstructor. And may be check also the other available AST annotations such as Immutable and Synchronized and perhaps also groovy.beans‘s Bindable and Vetoable annotations, if you need true Java Beans.

 

From http://theholyjava.wordpress.com/2011/11/02/groovy-use-canonical-to-get-compiler-generated-equals-hashcode-and-tostring/

Published at DZone with permission of Jakub Holý, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)