Groovy: Use @Canonical to Get Compiler-generated Equals, HashCode and ToString
Groovy makes it extremely easy to create Java beans with getters, setters, equals, hashCode, and toString:
You can then do:
As you might have noticed, you may provide your own implementation of toString and reuse the auto-generated toString by calling
@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()
.