将方法添加到元类

Lei*_*ngo 9 methods groovy metaprogramming metaclass

我只是在使用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()
Run Code Online (Sandbox Code Playgroud)

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

谢谢,Ingo

ata*_*lor 15

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

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

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

assert 'variable B'.printValueMethod() == "The value is: 'variable B'"
Run Code Online (Sandbox Code Playgroud)

在不使用闭包的情况下添加方法的自觉方法是创建一个类别类并将其混合起来:

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'"
Run Code Online (Sandbox Code Playgroud)

我不认为currying在这种特殊情况下可以提供帮助,因为在分配给元类时你不知道委托的价值.