1

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

class Dynamo extends Expando {
}

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

我想创建一个动态属性fullName评估为"$lastName, $firstName"

虽然它确实可以做到这一点:

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

它需要一个 call() 或隐式调用 with () 来返回字符串,否则它只是给出闭包 toString()

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

通行证

assert dynamic.fullName == 'dobbs, bob'

失败,因为计算结果为闭包的 toString

我总能做到这一点

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

但这并不干燥......

4

1 回答 1

1

For parameterless methods, Groovy needs parenthesis. I can think of two solutions:

Solution 1: Metaclass the getter getFullName:

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

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

assert dynamo.fullName == 'dobbs, bob'

Solution 2: Hook into the property getters with getProperty:

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

assert dyn2.fullName == 'doe, john'
于 2013-04-13T17:13:55.380 回答