Posts Tagged ‘ groovy annotations ’
Groovy annotations for ToString and EqualsAndHashCode
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.
@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass') @EqualsAndHashCode class Item { String name Float price boolean active = true Date dateCreated Date lastUpdated }
Before adding this annotation my domain class toString looks like this
Item item = new Item(name: "Chips", active: false, price: 15) println "To String output -: " + item //To String output -: com.intelligrape.myapp.Item : null
Now I get the following output for Item object toString
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)
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
@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 }
Hope it helps
## Uday Pratap Singh ##
uday@intelligrape.com
www.IntelliGrape.com/
in.linkedin.com/in/meudaypratap
Groovy Category Annotation
Annotations really provides a whole new view of programming things. Groovy also provides some of its own annotations one of them is Category. Lets take an example of using it. We create a IntegerUtil class and annotate it with Category.
@Category(Integer) class IntegerUtil { List<Integer> multiples(Integer upto) { (1..upto).collect {this * it} } }
Now the above code made your class any other groovy category class for example Time Category. Now you can use these methods as follows -:
List<Integer> multiples use(IntegerUtil) { multiples = 2.multiples(10) } println multiples // Output -: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
It really helps when you want some more helper methods on already existing classes.
Hope it helps
## Uday Pratap Singh ##
uday@intelligrape.com
www.IntelliGrape.com/
in.linkedin.com/in/meudaypratap