为元类添加方法

14

我只是在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()

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

谢谢, Ingo

1个回答

19

最简单的方法是将该方法封装在闭包中,像这样:

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'"

我认为在这种情况下,柯里化并不能提供帮助,因为你不知道将委托分配给元类时的值。


不错,谢谢。从没想过那个...是否也有一种方便的方法将许多静态辅助方法添加到类中(而不是通过类别)。例如,将Apache Commons IO FileUtils添加到文件类中? - Leikingo
啊...你的编辑也回答了我的附加问题。再次感谢。 - Leikingo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接