Those Groovy adepts who want to skip to the punchline can check out my best-seller JIRA ticket: “ExpandoMetaClass sometimes, but sometimes MetaClassImpl“.
For the rest of us, check out some odd behavior in Groovy.
class A {} def a = new A() a.metaClass.greet << { println "Hello, World!" } a.greet()
Looks great. Looks like a classic “Metaprogramming in Groovy” example, right down to including “Hello, World!”. So, I’m off to run it…
Exception thrown: groovy.lang.MissingPropertyException: No such property: greet for class: groovy.lang.MetaClassImpl groovy.lang.MissingPropertyException: No such property: greet for class: groovy.lang.MetaClassImpl at Script0.run(Script0:4)
WTF? Weird…where’s that “MetaClassImpl” come from? Where’d my ExpandoMetaClass go?
So, right after executing the first line, and I check out the metaClass attached to the class.
class A {} println A.metaClass.class.simpleName // prints "ExpandoMetaClass"
Okay, good, so I’ve got it. The awesome part is what comes next.
def a = new A() a.metaClass.greet << { println "Hello, World!" } a.greet() // prints "Hello, World!"
Hey, whaddyaknow? Now it works out great.
Turns out that you only get the ExpandoMetaClass if your class statically calls “.metaClass” before the variable is instantiated. Either that, or you need to call ExpandoMetaClass.enableGlobally().
Related posts:
Pingback: Enfranchised Mind » Functional (Meta)?Programming Stunts for Ruby and Groovy (and a Little Perl)
Pingback: Upped The Recent Post/Popular Post Widget Count | Enfranchised Mind
Pingback: The Blog’s Most Popular Posts | Enfranchised Mind