2017-08-01 62 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)