【发布时间】:2011-10-24 03:53:23
【问题描述】:
我现在正在试验 Groovy 闭包和委托。我有以下代码将闭包的委托设置为另一个类,效果很好。
def closure = {
newMethod()
};
closure.setDelegate(new MyDelegate());
closure.setResolveStrategy(Closure.DELEGATE_ONLY);
closure();
class MyDelegate {
public void newMethod() {
println "new Method";
}
}
这会打印出“new Method”,表明实际上调用了 MyDelegate 中的 newMethod()。现在我正在尝试对 MethodClosure 做同样的事情。
public class TestClass {
public void method() {
newMethod();
}
}
TestClass a = new TestClass();
def methodClosure = a.&method;
methodClosure.setDelegate(new MyDelegate());
methodClosure.setResolveStrategy(Closure.DELEGATE_ONLY);
methodClosure();
class MyDelegate {
public void newMethod() {
println "new Method";
}
}
但是,这一次,我得到了以下异常: 线程“主”groovy.lang.MissingMethodException 中的异常:没有方法签名:TestClass.newMethod() 适用于参数类型:() 值:[]。
所以对于这个methodClosure,它似乎根本不会去委托进行方法查找。我觉得这可能是预期的行为,但是有没有办法实际使用 MethodClosures 的委托?
非常感谢。
【问题讨论】:
标签: methods groovy delegates closures