问题
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?
回答1:
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()
回答2:
I can't seem to get this to work even after I added ExpandoMetaClass.enableGlobally() at the beginning of the script:
ExpandoMetaClass.enableGlobally();
Object.metaClass.static.Log = { msg ->
println(msg);
}
class Foo {
def l() {
Log("Foo:l().log"); // works
}
}
Object.Log("Object.log"); // works
String.Log("String.log"); // works
Log("script.log"); // works
foo = new Foo();
foo.l();
foo.Log("foo.log"); // works
Foo.Log("Foo.log") // Does not work
来源:https://stackoverflow.com/questions/1462946/groovy-meta-programming-adding-static-methods-to-object-metaclass