Another cool new feature of the recent Grails 0.4 release is the easy-to-use ExpandoMetaClass.  Groovy meta-programming is darn powerful stuff, and ExpandoMetaClass makes it super-simple to dynamically alter a class at runtime.  You can add instance methods, static methods, constructors, or properties, all in just a few short lines of code.  In fact, it's so cool that it's slated to become a standard part of Groovy in the Groovy 1.1 release slated for later this year.  

Enough chatter.  Let's see it in action. 

Here's some rather simple Groovy code that shows just how easy it is put the ExpandoMetaClass to work.  We simply define a class, instantiate it, add a new method to that class, and then the method is automatically available on the instance.

// A boring old class
class Canine {

// A boring old dog with no cool tricks
def oldDog = new Canine()

// If only a dog could speak
def canineMetaClass = new org.codehaus.groovy.grails.commons.metaclass.ExpandoMetaClass(Canine.class, true)
canineMetaClass.newTricks << { "Woof!" }

// Who say's you can't teach an old dog new tricks?!

And with a little help from the Grails console, we see that we can indeed teach an old dog new tricks (though teaching him to bark probably wouldn't be my first choice).

Grails Console output

While I'd known about the ExpandoMetaClass since Graeme Rocher committed it a few weeks back, it was Steven Devijver's post on the Grails mailing list today that inspired me to try it out.  (And though I wish I could take credit for the witty example, in fact, that credit goes to a co-worker of mine, Bill Dupre.  I showed Steven's post to Bill, and he quickly put this clever spin on it.)

What new tricks can your code libraries benefit from?