Dark theme | Light theme

November 29, 2009

Groovy Goodness: A Bit of metaClass DSL

When we add behaviour to classes with the metaClass property we can use a simple DSL. We pass a closure to the metaClass method where we group the definitions for the new behaviour. If we add multiple methods with the same name we must use <<, otherwise we can just set a closure to the method name. To add a static method we use 'static' and define the methods.

String.metaClass {
    or << { String s ->' or ').plus(s) }
    or << { List l -> delegate.findAll("(${l.join('|')})") }
    and { String s ->' and ').plus(s) }
    'static' {
        groovy { 'Yeah man!' }

assert 'Groovy or Java?' == ("Groovy" | "Java?")
assert ['o', 'o', 'y'] == ("Groovy" | ['o', 'y'])
assert 'Groovy and Java!' == ("Groovy" & "Java!")

assert 'Yeah man!' == String.groovy()