13

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()

メソッドを使用して、最初のパラメーターを呼び出し元のオブジェクトに設定することはできますか? デリゲートの使用は機能しないようです...呼び出し元を参照しないメソッドの割り当ては問題ありません。ここでカレーは機能しますか?

ありがとう、インゴ

4

1 に答える 1

18

これを実現する最も簡単な方法は、次のようにメソッドをクロージャーでラップすることです。

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

メタクラスへの割り当て時にデリゲートの値がわからないため、この特定のケースではカリー化が役立つとは思いません。

于 2010-12-10T18:45:06.843 に答える