Groovy ExpandoMetaClass getMetaMethods()不';t返回添加的方法
在调试Grails应用程序时,我发现Groovy的行为似乎有点奇怪。假设我想向Groovy ExpandoMetaClass getMetaMethods()不';t返回添加的方法,groovy,Groovy,在调试Grails应用程序时,我发现Groovy的行为似乎有点奇怪。假设我想向String类添加一些方法: String.metaClass.myMethod = { println 'Hello' } 然后我尝试使用getMetaMethods()获取元方法列表,但它不包含此方法。我知道有getExpandoMethods()可以正常工作,但添加到类中的元方法不应该也包含在metaMethods列表中吗?尤其是当getMetaMethod()按预期工作时。代码如下: def empt
String
类添加一些方法:
String.metaClass.myMethod = {
println 'Hello'
}
然后我尝试使用getMetaMethods()
获取元方法列表,但它不包含此方法。我知道有getExpandoMethods()
可以正常工作,但添加到类中的元方法不应该也包含在metaMethods
列表中吗?尤其是当getMetaMethod()
按预期工作时。代码如下:
def emptyArray = new Object[0];
assert String.metaClass.getMetaMethods().collect { it.name }.contains('myMethod') == false
assert String.metaClass.getMetaMethod('myMethod', emptyArray) != null
// and again with instance
def text2 = 'Just for testing...'
assert text2.metaClass.getMetaMethods().collect { it.name }.contains('myMethod') == false
assert text2.metaClass.getMetaMethod('myMethod', emptyArray) != null
如果我以前尝试使用expando方法,这就更奇怪了:
def text = 'Again just for testing...'
text.metaClass.getExpandoMethods() // strange, but let's try...
assert text.metaClass.getMetaMethods().collect { it.name }.contains('myMethod') == true
assert text.metaClass.getMetaMethod('myMethod', emptyArray) != null
使用Groovy 2.3.6和2.2.2进行测试
有什么想法吗?提前谢谢 在我看来,这似乎是一个bug——特别是由于上次调用
getExpandMethods
的副作用是它也被添加到了meta方法列表中。当查看groovy源代码时,我看到getMetaMethod('myMethod')
导致调用getMethodWithoutCaching
,这很有趣。也许这是一个缓存问题?我还没有运行您的代码,也不确定为什么该方法不在metaMethods属性中,但它几乎肯定会在methods属性中String.metaClass.methods.find{it.name=='myMethod'}
@Steinar感谢您的建议@JeffScottBrown谢谢,我知道可以使用getMethods()或getExpandMethods()检索此方法。不幸的是,我在尝试升级Grails时调试Grails应用程序时发现了这种行为。我已提交拉请求,希望它将被接受和合并-