替换为';这';在Groovy中调用方法引用

替换为';这';在Groovy中调用方法引用,groovy,closures,Groovy,Closures,从实例获取引用时,调用非静态方法引用很容易: class Foo { void funk() { println "okay!" } } Foo foo = new Foo() Closure closure = foo.&funk closure() // okay! is printed 但是,当方法引用是从类中获取时,如何替换这个 class Foo { void funk() { println "okay!" } } Foo foo = new Foo() Closure c

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

class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = foo.&funk
closure() // okay! is printed
但是,当方法引用是从类中获取时,如何替换
这个

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

以下解决了您的问题:

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

+1,特别是因为您刚刚向我介绍了
&
操作员!然而,这听起来很像一个复制品,它基本上声称这是不可能的。