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:
While will output:
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()
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.
No comments:
Post a Comment