【问题标题】:Set delegate of a MethodClosure in Groovy在 Groovy 中设置 MethodClosure 的委托
【发布时间】: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


    【解决方案1】:

    MethodClosures 实际上只是通过 Closure 接口调用方法的适配器。如您所见,它不进行委托。

    将 MyDelegate 用作委托的一种方法是将其混合,如下所示:

    TestClass a = new TestClass()
    a.metaClass.mixin MyDelegate
    def methodClosure = a.&method
    methodClosure()
    
    // or skip the closure altogether
    TestClass b = new TestClass()
    b.metaClass.mixin MyDelegate
    b.method()
    

    【讨论】:

    • 完全符合我的要求。完美!
    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 2023-03-26
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多