July 2013
Intermediate to advanced
370 pages
8h 27m
English
We saw how to inject methods into specific instances of a class in Section 13.3, 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) ... |
Read now
Unlock full access