13.2 Injecting Methods Using ExpandoMetaClass
To create domain-specific languages (DSLs), we need to be able to add arbitrary methods to different classes and even hierarchies of classes. We need to inject instance methods and static methods, manipulate constructors, and convert a method to a property for the sake of fluency. We’ll want these capabilities for creating mock objects to stand in for collaborators. In this section, we’ll discuss the techniques to alter and enhance a class’s structure.
We can inject methods into a class by adding methods to its MetaClass
. The methods we inject are available globally. We’re not restricted to a block like in categories. We discussed ExpandoMetaClass
in Section 12.2, Intercepting Methods Using ...
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.