Groovy annotations for ToString and EqualsAndHashCode

29 / Jan / 2012 by Uday Pratap Singh 4 comments

As I am a lazy programmer most of the time I dont implement toString and equals methods on my grails domain classes. I would like to say thanks to Groovy for helping me out and giving me a ready made recipe for this. Now I just need to annotate my class with ToString and EqualAndHashCode annotation it adds appropriate implementation of these methods for me. Now My domain class looks something like this.

[java]
@ToString(includeNames = true, includeFields = true, excludes = ‘dateCreated,lastUpdated,metaClass’)
@EqualsAndHashCode
class Item {
String name
Float price
boolean active = true
Date dateCreated
Date lastUpdated
}
[/java]

Before adding this annotation my domain class toString looks like this

[java]
Item item = new Item(name: "Chips", active: false, price: 15)
println "To String output -: " + item //To String output -: com.intelligrape.myapp.Item : null
[/java]

Now I get the following output for Item object toString

[java]
Item item = new Item(name: "Chips", active: false, price: 15)
println "To String output -: " + item //To String output -: com.intelligrape.myapp.Item(name:Chips, price:15.0, active:false)
[/java]

To get this annotation on all my domain classed I updated the template of grails domain classes so that whenever I do create-domain-class it give me the annotated domain classes

[java]
@artifact.package@
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@ToString(includeNames = true, includeFields = true, excludes = ‘dateCreated,lastUpdated,metaClass’)
@EqualsAndHashCode
class @artifact.name@ {

Date dateCreated
Date lastUpdated
}
[/java]

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Sergey Ponomarev

    Hi, Uday,

    I have Grails domain class annotated with @ToString(includes = [‘id’]), i.e. I would like to see id of object in toString() output.
    But it not printed. I tried to create usual, not domain class with id field in toString() – all works fine.
    Maybe you know the reason why it happens?

    Thanks

    Reply
  2. Uday Pratap Singh

    I looked at it when I added these two separately. But yes its make more sense here although it also gives me the functionality of TupleConstructor which I wouldn’t mind to have in my class 😉

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *