...
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:.
| Note |
|---|
| title | For Groovy version 1.6 and higher |
|---|
|
See "What's New in Groovy 1.6" |
| Code Block |
|---|
def str = "hello"
str.metaClass.test = { "test" }
assert "test" == str.test()
|
| Note |
|---|
| title | For Groovy prior to version 1.6 |
|---|
|
|
| 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" }
emc.initialize()
gstr.metaClass = emc
gstr.test() // prints "test"
|
...