Invoking a non-static method reference is easy when the reference is obtained from an instance:
class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = foo.&funk
closure() // okay! is printed
But how to substitite this
when the method reference is obtained from a class?
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
The following solves your problem:
class Foo { void funk() { println "okay!" } }
Closure closure = { Foo.&funk.rehydrate(delegate, it, it).call() }
Foo foo = new Foo()
closure(foo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With