Since Groovy 1.8 we can use the @ToString
annotation for easy creation of a toString()
method. We only have to add the annotation to our class definition and we get a nicely formatted output of the properties of our class.
We can even customize what we want to see in the output. We can see the names of the properties of our class in the toString()
output if we add the attribute includeNames=true
. By default only properties are added to the output, but we can include fields as well with the annotation attribute includeFields=true
.
To exclude properties we use the attribute excludes
and assign the names of the properties we don't want in the output separated by a comma.
Finally we can include properties from a super class with the annotation atribute includeSuper=true
.
Let's see the @ToString
in action with a few samples:
// Most simple implementation of toString. import groovy.transform.ToString @ToString class Person { String name List likes private boolean active = false } def person = new Person(name: 'mrhaki', likes: ['Groovy', 'Java']) assert person.toString() == 'Person(mrhaki, [Groovy, Java])'
// includeNames to output the names of the properties. import groovy.transform.ToString @ToString(includeNames=true) class Person { String name List likes private boolean active = false } def person = new Person(name: 'mrhaki', likes: ['Groovy', 'Java']) assert person.toString() == 'Person(name:mrhaki, likes:[Groovy, Java])'
// includeFields to not only output properties, but also field values. import groovy.transform.ToString @ToString(includeNames=true, includeFields=true) class Person { String name List likes private boolean active = false } def person = new Person(name: 'mrhaki', likes: ['Groovy', 'Java']) assert person.toString() == 'Person(name:mrhaki, likes:[Groovy, Java], active:false)'
// Use includeSuper to include properties from super class in output. import groovy.transform.ToString @ToString(includeNames=true) class Person { String name List likes private boolean active = false } @ToString(includeSuper=true, includeNames=true) class Student extends Person { List courses } def student = new Student(name: 'mrhaki', likes: ['Groovy', 'Java'], courses: ['IT', 'Business']) assert student.toString() == 'Student(courses:[IT, Business], super:Person(name:mrhaki, likes:[Groovy, Java]))'
// excludes active field and likes property from output import groovy.transform.ToString @ToString(includeNames=true, includeFields=true, excludes='active,likes') class Person { String name List likes private boolean active = false } def person = new Person(name: 'mrhaki', likes: ['Groovy', 'Java']) assert person.toString() == 'Person(name:mrhaki)'