ExpandoMetaClasses

We briefly touched on metaclasses when building our Twitter DSL in Chapter 4, The Groovy Language. In the coming example, we've used String.metaClass to dynamically add a method to the String class for Twitter searching. Let's look at what is happening here:

String.metaClass.search = { Closure c ->
   GeeTwitter.search(delegate,c)
}

From the earlier section on expandos, we understand how an Expando allows us to dynamically add a property to a class. That's all that is happening here. In the preceding code, we are dynamically adding a property to MetaClass for String in the same way as we added properties to Expando. This property happens to be a Closure, and the object happens to be the MetaClass of String, so it has the effect of ...

Get Groovy for Domain-specific Languages - Second Edition 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.