Sunday, August 22, 2010

Adding StringUtils to the String Class in Groovy/Grails

This one has been blogged about before - but I thought it was just such an easy way to add very useful functionality to the String class that I thought I would call it out.

I had the need to use the Apache StringUtils methods so often in my application that I started to wish that the methods were just native to the String class. Adding this kind of capability is called mixins in Groovy.

To check if a string is null, empty or whitespace, with the Apache package you have to write:

If( StringUtils.isBlank( myStringToCheck) ) {
// then is blank
}

what I wanted to do was:

if( myStringToCheck.isBlank() ) {
// then is blank
}

I just thought this was easier to read and easier to write.

This is actually incredibly easy to do in Groovy/Grails.

The way I went about do this was to add the following line of code to the Bootstrap.groovy file:

// add apache commons lang StringUtils methods to the String class
String.metaClass.mixin StringUtils

add the commons-lang jar file to the lib directory and that is it.

Now for any String I can use any of the methods in the StringUtils package as though they were native methods to the String class.

Nice!