问题
I have a short snippet where I try to delegate the variable resolution to the delegate. However the delegates value isnt used, instead the owners value is used. Is this intentional or is this a bug?
class Person {
int age
}
def age = -5
def closure = { -> age }
closure.delegate = new Person(age: 99)
closure.resolveStrategy == Closure.DELEGATE_ONLY
assert closure.call() == 99
Above code fails, with the closure returning -5.
回答1:
Your code returns -5
because the variable age
is defined withing the lexical scope of the closure, meaning that the closure can use the value of the variable age
.
You have to explicitly tell the closure to use the age property of the delegate:
def closure = { -> delegate.age }
Try the following code:
class Person {
int age
}
def age = -5
def closure = { -> delegate.age * age }
closure.delegate = new Person(age: 99)
closure.resolveStrategy == Closure.DELEGATE_ONLY
assert closure.call() == 99*-5
来源:https://stackoverflow.com/questions/32368483/groovy-delegates-working-as-intended