My Octopress Blog

A blogging framework for hackers.

Groovy MetaProgramming

While working on a Grails project I started investigating groovy meta-programming. I wanted to be able to add one method per class for every Enum in the containing class. (I’ll have an example below)

The official groovy documentation on the topic is here: http://groovy.codehaus.org/ExpandoMetaClass

Most examples show something like the following:

//Add new method call printHello
SomeClass.metaClass.printHello = { print "Hello" }
def instance = new SomeClass()

Which of course when run will print “Hello”.

However, I didn’t know the method was called at runtime, I just wanted to add one for every entry in an enum. It’s not hard, but there isn’t an example out there, after a little playing in the groovy console, I figured it out:

enum Status {A,B,C}

class User{
def status
}

Status.each{ statusEnum ->
User.metaClass."is${statusEnum.name()}" = {
return status == statusEnum
}
}

def user = new User()
println user.isA()
user.status = Status.A
println user.isA()
println user.isB()
user.status = Status.B
println user.isB()
While will output:

false
true
false
true

Of course, this isn’t exactly complex, and I may find that I don’t like how this turns out, but I couldn’t find an example of this type of Groovy meta-programming example, so I thought I would share.