2016-07-12 85 views
1

我是新來groovy和學習從this關閉指南。代表團戰略Groovy

每當在閉包中訪問某個屬性而未明確設置接收者對象時,就會涉及委託策略。

不應該返回ALLAUDIN。我在哪裏做錯了?

class Example { 

class Person { 
String name 
Person(String name){ 
    this.name = name 
} 
} 

class Thing { 
String name 
Thing(String name){ 
    this.name = name 
} 
} 


static void main(String[] args){ 
    Example e = new Example(); 

    def p = new Person(e, 'allaudin') 
    def t = new Thing(e, 'laptop') 

    def getUpperName = { name.toUpperCase() } 
    getUpperName.delegate = p 
    println getUpperName() // EXAMPLE 

} 

}

回答

3

您需要設置delegation strategy

添加一行:

getUpperName.resolveStrategy = Closure.DELEGATE_FIRST 

你在哪裏設置委託