Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference the GroovyObject instance from MetaClass methods in Groovy?

This is a contrived example of what I want to do, but minimally expresses the behavior desired. I want to reference the instance of the object on which the property access is being invoked. I tried 'this' first, but that refers to the enclosing class rather than either the MetaClass or the String instance.

String.metaClass.propertyMissing = { String name ->
    'I do not exist, but my name is ' + <the String instance> + '.' + $name
}
like image 222
Phil Avatar asked Feb 15 '09 02:02

Phil


1 Answers

You can refer to the object with "delegate":

String.metaClass.propertyMissing = { String name ->
    "I do not exist, but my name is $delegate.$name"
}


println "a".me
like image 193
chanwit Avatar answered Nov 08 '22 05:11

chanwit