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.
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.
" 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.
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
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