从实例获取引用时,调用非静态方法引用很容易:
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
答案 0 :(得分:3)
以下解决了您的问题:
class Foo { void funk() { println "okay!" } }
Closure closure = { Foo.&funk.rehydrate(delegate, it, it).call() }
Foo foo = new Foo()
closure(foo)