Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute 'this' invoking a method reference in Groovy

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
like image 818
Pavel Vlasov Avatar asked Oct 21 '22 17:10

Pavel Vlasov


1 Answers

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)
like image 112
akhikhl Avatar answered Oct 24 '22 01:10

akhikhl