方法 – 将方法添加到元类
发布时间:2020-12-14 16:30:31 所属栏目:大数据 来源:网络整理
导读:我正在玩Groovy中的元编程.但是突然间我面临一些我不能工作的小问题 这是简单的脚本: // define simple closuredef printValueClosure = { println "The value is: '$delegate'"}String.metaClass.printValueClosure = printValueClosure// works fine'vari
我正在玩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() 是否可以使用该方法,但是将第一个参数设置为调用对象?使用委托似乎不工作…不引用调用方的方法的分配没有问题.在这里工作吗 谢谢, 解决方法
完成此操作的最简单方法是将方法包装在闭包中,如下所示:
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'" 在这种特殊情况下,我不认为currying可以帮助,因为在分配给元类时,你不知道代表的价值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |