Chapter 7
[ 169 ]
Conveniently, this pattern is the same as the one used in Groovy categories, which
means that the Apache Commons Lang Util classes can all be dropped straight into
a use block. So all of these useful utility classes are ready to be used in your Groovy
code as categories:
import org.apache.commons.lang.StringUtils
expect:
use (StringUtils) {
"org.apache.commons.lang3".split(".") ==
["org", "apache", "commons", "lang3"]
}
You can also use the @Category annotation in association with
a class.
Traits
A recent and very useful addition to the Groovy language is the concept of a trait.
A trait is a reusable set of methods and properties that can be applied to any class
without the need for multiple inheritance. Earlier in the chapter, we implemented a
pretty print class for the Customer class. In the following example we implement the
PrettyPrintable class as a trait. This trait can be applied to any class to give it the
ability to pretty print its properties:
trait PrettyPrintable {
void prettyPrint() {
this.properties.sort { it.key }.each {
if (it.key != 'prettyPrint' && it.key != 'class')
println it.key + ": " + it.value
}
}
}
class Customer implements PrettyPrintable {
int id
String firstName
String surname
String street
String city
}