13.3 Injecting Methods into Specific Instances
We saw ways to inject methods into a class dynamically. We can add behavior to specific instances of a class much like how we added behavior to the class.
Suppose we receive a Person and, based on
a certain condition or state, we want to perform some operations on it. We figure it would be easier to
inject a set of reusable methods or utility functions on it; however, we don’t want to apply those globally
on all Persons. Groovy makes it fairly simple to inject instances with methods.
The MetaClass is per-instance. If we want an instance to have a different behavior than the other objects instantiated from the same class, we inject the methods into the metaClass obtained from the specific ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access