替换'this'在Groovy中调用方法引用

时间:2013-12-30 15:19:44

标签: groovy closures

从实例获取引用时,调用非静态方法引用很容易:

class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = foo.&funk
closure() // okay! is printed

但是当从类中获取方法引用时如何替换this

class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = Foo.&funk
// closure.delegate = foo // not helpful
closure()
// => java.lang.IllegalArgumentException: object is not an instance of declaring class

1 个答案:

答案 0 :(得分:3)

以下解决了您的问题:

class Foo { void funk() { println "okay!" } }
Closure closure = { Foo.&funk.rehydrate(delegate, it, it).call() }
Foo foo = new Foo()
closure(foo)