从地图更新常规对象字段 [英] Updating groovy object fields from a map
本文介绍了从地图更新常规对象字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 groovy 中,我们可以轻松地从地图创建对象并自动填充相应的字段:
In groovy we can easily create objects from maps and fill the corresponding fields automatically:
def myAddress = new Address([street:"King's street", number:"1200"])
是否也可以在不重新创建地图的情况下更新现有对象?像……
Is it possible to also update an existing object from a map without recreating it? Something like...
myAddress.update([zip: "30555050", city: "London"])
推荐答案
您可以使用 object."${variable}"
访问器来做到这一点:
You can use object."${variable}"
accessors to do this:
map.each { key, value ->
object."${key}" = value
}
然后您可以创建一个执行此操作的方法并将其安装在 Object.metaClass 上,它将随处可用:
You can then create a method that does this and install that on Object.metaClass and it will be available everywhere:
@Canonical
class MapSet {
String name
int count
static def setAttributesFromMap(Object o, Map<String, Object> map) {
map.each { key, value ->
o."${key}" = value
}
}
static void main(String[] args) {
Object.metaClass.update = {
setAttributesFromMap delegate, it
}
def o = new MapSet([
name: "foo",
count: 5
])
assert o.name == "foo"
assert o.count == 5
o.update([
name: "bar",
count: 6
])
assert o.name == "bar"
assert o.count == 6
}
}
这篇关于从地图更新常规对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文