views:

655

answers:

1

I've encountered a Groovy meta-programming problem which I'm unable to solve.

When adding the static method foo() to the class FooBar, then FooBar.foo() works as expected:

FooBar.metaClass.static.foo = {
    println "hello"
}
FooBar.foo()

However, I instead add the same static method foo() to the class Object, then FooBar.foo() fails with an MissingMethodException:

Object.metaClass.static.foo = {
    println "hello"
}
FooBar.foo()
// groovy.lang.MissingMethodException:
// No signature of method: FooBar.foo() is applicable for argument types: 
// () values: []

Why is that? Shouldn't Object.metaClass.static.foo = { .. } add foo() also to FooBar?

+7  A: 

In order to get the behavior you're looking for you need to call ExpandoMetaClass.enableGlobally()

Keep in mind doing this has a bigger memory footprint than normal meta-programming.

http://groovy.codehaus.org/api/groovy/lang/ExpandoMetaClass.html#enableGlobally()

Rhysyngsun
Hi! Judging from the docs this should be the correct answer, but the exception is still thrown even when ExpandoMetaClass.enableGlobally() is run in the start of the Groovy script. Have you been able to inject a static method to Object and have it available to extending objects?
knorv