Groovy Goodness: Customize ToString Creation
The @ToString
AST transformation has several parameters we can define to customize the generated code for the toString
method. We have already seen some of the parameters in an earlier blog post, but in new Groovy releases some extra parameters were added.
For example we can leave out the package name of the class with the parameter includePackage
. If we set the value to false
the package name is not included:
package com.mrhaki.blog.groovy
import groovy.transform.*
@ToString(includePackage=false /* default true */)
class Course {
String title
Integer maxAttendees
}
final Course course = new Course(title: 'Groovy 101', maxAttendees: 200)
assert course.toString() == 'Course(Groovy 101, 200)'
We can skip properties with null
value from the toString
method output with the paramater ignoreNulls
:
package com.mrhaki.blog.groovy
import groovy.transform.*
@ToString(ignoreNulls=true /* default false */)
class Course {
String title
Integer maxAttendees
}
final Course course = new Course(title: 'Groovy 101')
assert course.toString() == 'com.mrhaki.blog.groovy.Course(Groovy 101)'
And since Groovy 2.1 we can cache the result of toString
when we know the class is immutable or at lease we know the values won't change:
package com.mrhaki.blog.groovy
import groovy.transform.*
@ToString(cache=true /* default false */)
class Course {
String title
Integer maxAttendees
}
Course course = new Course(title: 'Groovy 101', maxAttendees: 200)
assert course.toString() == 'com.mrhaki.blog.groovy.Course(Groovy 101, 200)'
// Value change will not be reflected in toString().
course.title = 'Grails with REST'
assert course.toString() == 'com.mrhaki.blog.groovy.Course(Groovy 101, 200)'
assert course.title == 'Grails with REST'
Code written with Groovy 2.2.2.