2017-08-01 96 views
0

這是這個問題我的示例代碼:如何訪問groovy中的委託對象屬性?

class Person { 
    String fullName 
} 

def myClosure = { 
    fullName = "Chakroun Anas" 
} 

Person person = new Person() 
myClosure.delegate = person 
myClosure() 
println(person.fullName) 

這是輸出:

null 

所以是有可能從封閉訪問委託對象的屬性?如果是的話那怎麼樣?

在此先感謝。

回答

0

考慮這個(使用this page作爲參考):

class Person { 
    String fullName 
} 

def myClosure = { 
    fullName = "Chakroun Anas" 
} 

Person person = new Person() 

myClosure.resolveStrategy = Closure.DELEGATE_FIRST 
myClosure.delegate = person 
myClosure() 

println(person.fullName)