将Groovy Closure注入作为Property的Expando

时间:2013-04-13 16:45:59

标签: groovy closures expando

我有一个扩展Expando并注入动态属性的类。

class Dynamo extends Expando {
}

Dynamo dynamic = [ firstName: 'bob', lastName: 'dobbs' ]

我想创建一个动态属性 fullName ,其值为“$ lastName,$ firstName”

虽然它可以做到这一点:

dynamic.fullName = { "$lastName, $fullName" }

它需要使用call()或带()的隐式调用来返回字符串,否则它只是给闭包toString()

assert dynamic.fullName() == 'dobbs, bob'

通行证

但是

assert dynamic.fullName == 'dobbs, bob'

失败,因为它会计算闭包的toString

我总是可以这样做

Dynamo dynamic = [ firstName: 'bob', lastName: 'dobbs', fullName: 'dobbs, bob' ]

但那不是干......

1 个答案:

答案 0 :(得分:1)

对于无参数方法,Groovy需要括号。我可以想到两个解决方案:

解决方案1:元素化吸气剂getFullName

Dynamo dynamo = [ firstName: 'bob', lastName: 'dobbs' ]

dynamo.metaClass.getFullName = { "$lastName, $firstName" }

assert dynamo.fullName == 'dobbs, bob'

解决方案2:使用getProperty进入属性getter:

Dynamo dyn2 = [ firstName: 'john', lastName: 'doe' ]
dyn2.metaClass.getProperty = { String property ->
    if (property == "fullName") { 
        "${delegate.lastName}, ${delegate.firstName}" 
    } 
}

assert dyn2.fullName == 'doe, john'