Groovy元编程 - 将静态方法添加到Object.metaClass [英] Groovy meta-programming - adding static methods to Object.metaClass

查看:120
本文介绍了Groovy元编程 - 将静态方法添加到Object.metaClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当将静态方法foo()添加到类FooBar中时,那么FooBar.foo()按预期工作:

  FooBar.metaClass.static.foo = {
printlnhello

FooBar.foo()

然而,我反而添加了相同的静态方法foo()到类Object中,然后FooBar.foo()失败并带有MissingMethodException:

  Object.metaClass.static .foo = {
printlnhello
}
FooBar.foo()
// groovy.lang.MissingMethodException:
//方法的签名:FooBar .foo()适用于参数类型:
//()values:[]

为什么呢?不应该 Object.metaClass.static.foo = {..} 将foo()也添加到FooBar中?

解决方案

为了获得您要查找的行为,您需要调用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()

这篇关于Groovy元编程 - 将静态方法添加到Object.metaClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆