13

我只是在玩 Groovy 中的元类编程。但是突然间我遇到了一个小问题,我无法开始工作......

这是简单的脚本:

// define simple closure
def printValueClosure = {
 println "The value is: '$delegate'"
}

String.metaClass.printValueClosure = printValueClosure

// works fine
'variable A'.printValueClosure()



// define as method
def printValueMethod(String s){
 println "The value is: '$s'"
}

// how to do this!?
String.metaClass.printValueMethod = this.&printValueMethod(delegate)

'variable B'.printValueMethod()

是否可以使用该方法但将第一个参数设置为调用对象?使用委托似乎不起作用......不引用调用者的方法的分配没有问题。咖喱在这里有用吗?

谢谢,英戈

4

1 回答 1

18

完成此操作的最简单方法是将方法包装在闭包中,如下所示:

def printValueMethod(String s){
    println "The value is: '$s'"
}

String.metaClass.printValueMethod = { -> printValueMethod(delegate) }

assert 'variable B'.printValueMethod() == "The value is: 'variable B'"

在不使用闭包的情况下添加方法的惯用方法是创建一个类别类并将其混合,如下所示:

class PrintValueMethodCategory {
    static def printValueMethod(String s) {
        println "The value is: '$s'"
    }
}

String.metaClass.mixin(PrintValueMethodCategory)

assert 'variable B'.printValueMethod() == "The value is: 'variable B'"

我认为柯里化在这种特殊情况下没有帮助,因为您在分配给元类时不知道委托的值。

于 2010-12-10T18:45:06.843 回答