从实例获取引用时,调用非静态方法引用很容易:
class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = foo.&funk
closure() // okay! is printed
Run Code Online (Sandbox Code Playgroud)
但是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
Run Code Online (Sandbox Code Playgroud)
以下内容解决了您的问题:
class Foo { void funk() { println "okay!" } }
Closure closure = { Foo.&funk.rehydrate(delegate, it, it).call() }
Foo foo = new Foo()
closure(foo)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
739 次 |
| 最近记录: |