Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Normally when you add a MetaMethod, it is added for all instances of that class. However, for GroovyObjects, you can dynamically add methods to individual instances by giving that instance its own MetaClass.


For Groovy version 1.6 and higher


- any Groovy or Java object

Code Block
def str = "hello"
str.metaClass.test = { "test" }
assert "test" == str.test()

For Groovy prior to version 1.6 - GroovyObjects only!

Code Block
def test = "test"
def gstr = "hello $test"     // this is a GString, which implements GroovyObject

def emc = new ExpandoMetaClass( gstr.class, false )
emc.test = { println "test" }

gstr.metaClass = emc
gstr.test()                  // prints "test"