Search code examples
groovytemplate-enginefrontendextend

Extending Groovy String class


Groovy allows to do some nice things with strings in frontend pages, like:

${"hello".capitalize()}

How can I add a new custom method to the String class? Like:

${"hello".custom()}


Solution

  • Use the metaClass

    String.metaClass.custom = { //dosomething }
    

    See http://www.groovyexamples.org/2010/07/19/dynamically-add-properties-to-a-class/