且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Groovy元编程 - 将静态方法添加到Object.metaClass

更新时间:2023-12-03 07:53:10

为了获得您要查找的行为,您需要调用ExpandoMetaClass.enableGlobally()



请记住这比普通的元编程有更大的内存占用。

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


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?

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()