Groovy meta-programming - adding static methods to Object.metaClass

[亡魂溺海] 提交于 2020-01-01 09:27:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!