December 21, 2009

Groovy Goodness: Override and Use Old Implementation with Dynamic Methods

We can add new methods to classes with the metaClass property. But what if we want to use the old implementation for some cases? We can save the original method implementation in a variable and use it in our new implementation. The best way to get the original method is to access metaClass and invoke the getMetaMethod() method. We save this method in a variable. In the new implementatation we can use the invoke() method on the saved method to invoke the original code.

def savedToUpperCase = String.metaClass.getMetaMethod('toUpperCase', [] as Class[])
String.metaClass.toUpperCase = { -> 
    def result = savedToUpperCase.invoke(delegate)    
    if (delegate =~ /Groovy/) {
        result + ' Oh, yeah man! Groooovy...'
    } else {

assert 'A SIMPLE STRING' == 'A simple string'.toUpperCase()
assert 'THIS IS GROOVY. Oh, yeah man! Groooovy...' == 'This is Groovy.'.toUpperCase()