[英]Groovy Closure methods don't take precedence does not seem to get called when in a class
我只是不明白如何讓閉包像我期望的那樣工作。 例如,假設我有一堂課
class Bar {
public void greeting(String name) {
println "Hello: ${name}"
}
}
當我在Closure
中委托Bar
時:
class Foo {
void helloBob(){
bar {
greeting("Bob")
}
}
def bar(@DelegatesTo(value = Bar, strategy = Closure.DELEGATE_ONLY) Closure cl) {
cl.rehydrate(new Bar(), this, this)
cl.call()
}
static void main(String[] args) {
new Foo().helloBob()
}
}
運行時我得到堆棧跟蹤:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: Foo.greeting() is applicable for argument types: (String) values: [Bob]
Possible solutions: getAt(java.lang.String)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:70)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:76)
at
at ...
: No signature of method: Foo.greeting()
對我來說沒有意義,因為它應該調用Bar.greeting()
,因為它位於具有@DelegatesTo(value = Bar
的Closure
包中。為什么閉包不引用Bar.greeting
?我如何讓它做到這一點?我的 IDE(IntelliJ)似乎認為它是我想要的Bar.greeting
,但是當我運行它時,我得到了一個堆棧跟蹤。
編輯很奇怪,如果我刪除了一大堆類型信息,那么它似乎可以使用:
Bar bar(closure) {
def bar = new Bar()
closure.delegate = bar
// closure.rehydrate(bar, this, this) // this causes error why?
closure.call()
return bar
}
有了 IDE,一切順利。 我也不明白為什么我不能使用rehydrate
似乎會導致錯誤,但手動設置delegate
就可以了。
Rehydrate 不會修改閉包 - 它會返回它的新副本。 所以調用新的閉包。
cl.rehydrate(new Bar(), this, this).call()
不要忘記將 resolveStrategy 設置為您在注釋中聲明的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.