Book Image

Groovy for Domain-Specific Languages, Second Edition

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages, Second Edition

By: Fergal Dearle

Overview of this book

Table of Contents (20 chapters)
Groovy for Domain-specific Languages Second Edition
About the Author
About the Reviewers
Free Chapter
Introduction to DSLs and Groovy


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: = { Closure c ->,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 adding a new method to the String class.

Adding a regular property to MetaClass can be achieved in the same way as with expandos. There is only a single MetaClass per Groovy or Java class, so this is useful only if we have a new property that...