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 instance. ...

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.