Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Customize ToString Creation

DZone's Guide to

Groovy Goodness: Customize ToString Creation

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}