Friday, June 01, 2007

Dynamic Groovy: Groovy's Equivalent to Ruby Open Classes

A lot of hype has been made of Ruby's open classes, and for good reason as they're pretty darn cool. Since Groovy classes compile down to byte code (ie a Groovy class is a Java class) it has always been a little more problematic to add dynamic features to classes you don't have control over.

If you're the class implementor for example you could override invokeMethod and getProperty, but if you're not your only option was Groovy categories, which aren't nearly as elegant, or implementing your own custom MetaClass which exposed you to Groovy internals and wasn't very fun.

However, this is all changing because I've just committed major improvements and written the documentation for Groovy's dynamic meta class mechanism, the ExpandoMetaClass. This is the system I discussed with Neal Ford at JavaOne who felt, prior to our discussion, that Ruby had the upper hand because of open classes. After our discussion and a short demo of what ExpandoMetaClass is capable of, Neal changed his mind and upgraded Groovy's rating on his language scale.

So in the next beta release, you'll see a new improved version of ExpandoMetaClass with features such as:
Here is a little example:

String.metaClass.swapCase = {->
def sb = new StringBuffer()
delegate.each {
sb << (Character.isUpperCase(it as char) ?
Character.toLowerCase(it as char) :
Character.toUpperCase(it as char))
}
sb.toString()
}
assert "UpAndDown" == "uPaNDdOWN".swapCase()

ExpandoMetaClass has been at the heart of Grails for a while, so is completely production ready. Now its time to bring it to the masses with the next beta release of Groovy targeted for the end of June.

5 comments:

Anonymous said...

Totally wicked! specially the borrowing method bit. This is much better than the trick with aliases described in GINA, you can even modify final classes (as the example showed with String).

Anonymous said...

It's witchcraft.

Anonymous said...

... but in a good way. :-)

Anonymous said...

Sorry Sir for asking, but may I ask you to check :
http://www.nabble.com/create-app-fails-tf3887044.html
Thanks for your time.

Anonymous said...

My father was very like to play the Aion, but he do not know how to buy the aion gold, so I know a website sell the cheap aion gold, in here I can buy aion gold. it is easy.