Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the caller object of a closure in groovy?

Is it possible to get a reference of the Object that invoked a Closure in the Closure's execution context?

For example:

public class Example {

    public Example(){
        def a = {return this};
        def b = [];

        b.metaClass.a = a;

        println b.a();
    }
}

I want this execution to return b instead of an instance of Example.

like image 895
David Paulo Avatar asked Aug 28 '12 21:08

David Paulo


People also ask

How do you call closure on Groovy?

Closures can also contain formal parameters to make them more useful just like methods in Groovy. In the above code example, notice the use of the ${param } which causes the closure to take a parameter. When calling the closure via the clos. call statement we now have the option to pass a parameter to the closure.

What is this in Groovy?

" this " in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). " owner " is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as " this ", or another Closure.


1 Answers

The object that the closure is invoked on can be referenced as delegate. Example:

def a = { return delegate }
def b = []

b.metaClass.a = a

assert b.a() == b
like image 181
ataylor Avatar answered Oct 13 '22 06:10

ataylor