O'Reilly logo

Groovy for Domain-specific Languages - Second Edition by Fergal Dearle

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required