Synthesizing Methods for Specific Instances

We saw how to inject methods into specific instances of a class in Injecting Methods into Specific Instances. We can dynamically synthesize methods into specific instances, as well, by providing the instance(s) with a specialized MetaClass. Here is an example:

InjectionAndSynthesisWithMOP/SynthesizeInstance.groovy
 
class​ Person {}
 
 
def​ emc = ​new​ ExpandoMetaClass(Person)
 
emc.methodMissing = { ​String​ name, args ->
 
"I'm Jack of all trades... I can ​$name​"
 
}
 
emc.initialize()
 
 
def​ jack = ​new​ Person()
 
def​ paul = ​new​ Person()
 
 
jack.metaClass = emc
 
 
println jack.sing()
 
println jack.dance()
 
println jack.juggle()
 
 
try​ {
 
paul.sing()
 
} ​catch​(ex) {
 
println ex
 
}

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.