将方法添加到元类 [英] Add method to metaclass
问题描述
我只是在玩Groovy中的元类编程。但突然之间,我遇到了一个小问题,我无法工作......
以下是简单的脚本:
//定义简单封闭
def printValueClosure = {
println值为:'$ delegate'
}
String.metaClass.printValueClosure = printValueClosure
//正常工作
'变量A'.printValueClosure()
//定义为方法
def printValueMethod(String s){
println值为:'$ s'
}
//如何操作这个!?
String.metaClass.printValueMethod = this。& printValueMethod(delegate)
'variable B'.printValueMethod()
是否可以使用该方法但将第一个参数设置为调用对象?使用委托似乎不工作...不引用调用方法的方法的分配是没有问题的。在这里做咖啡的工作吗?
谢谢,
Ingo
最简单的方法是将方法封装在闭包中,如下所示:
def printValueMethod(String s) {
println值为:'$ s'
}
String.metaClass.printValueMethod = { - > printValueMethod(委托)}
assert'变量B'.printValueMethod()==值为:'变量B'
添加一个方法而不使用闭包的习惯方法是创建一个类别类并将其混合,如下所示:
class PrintValueMethodCategory {
static def printValueMethod(String s){
println值为:'$ s'
}
}
String.metaClass.mixin(PrintValueMethodCategory)
assert'变量B'.printValueMethod()==值为:'变量B''
我不认为在这种特殊情况下,咖喱会有帮助,因为您不知道代理的价值分配给元类的时间。
I'm just playing with the metaclass programming in Groovy. But suddenly I was facing a little problem which I just could not get working...
Here is the simple script:
// 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()
Is it possible to use the method but set the first parameter to the calling object? using delegate seems not to work... The assignment of methods which do not reference the caller is no problem. Does currying work here?
Thanks, Ingo
The simplest way to accomplish this is to wrap the method in a closure, like so:
def printValueMethod(String s){
println "The value is: '$s'"
}
String.metaClass.printValueMethod = { -> printValueMethod(delegate) }
assert 'variable B'.printValueMethod() == "The value is: 'variable B'"
The idomatic way to add a method without using closures would be to create a category class and mix it in like so:
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'"
I don't think currying can help in this particular case, since you don't know the value of the delegate at the time of assignment to the metaclass.
这篇关于将方法添加到元类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!