【问题标题】:Add method to metaclass向元类添加方法
【发布时间】:2011-05-23 15:31:04
【问题描述】:

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

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

谢谢, 英戈

【问题讨论】:

    标签: methods groovy metaprogramming metaclass


    【解决方案1】:

    实现这一点的最简单方法是将方法包装在闭包中,如下所示:

    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 到文件类?
    • 啊...您的编辑也回答了我的附加问题。再次感谢。
    猜你喜欢
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多