我不确定我哪里出错了,但似乎我无法从对象实例复制属性并将它们分配给 map ,而不在保存实例后更改值。
这是一个示例类:
class Product {
String productName
String proudctDescription
int quantityOnHand
}
提交表单并将其发送到我的 Controller 后,我可以访问值并从实例可用的 productInstance.properties
映射中操作它们。我想将属性复制到另一个 map 以在编辑期间提交它们之前保留这些值。假设我们正在编辑一条记录,这些是存储在数据库中的值:productName = "My Product"
、productDescription = "My Product Description"
和 数量OnHand = 100
。
我想将它们复制到:
def propertiesBefore = productInstance.properties
这不起作用,因为当我保存 productInstance 时,propertiesBefore 中的值更改为实例所具有的值。
所以我尝试了这个:
productInstance.properties.each { k,v -> propertiesBefore[k] = v }
同样的事情又发生了。我不确定如何按值复制,似乎无论我尝试什么,它都是按引用复制。
编辑
应 Pawel P. 的要求,这是我测试的代码:
class Product {
String productName
String productDescription
int quantityOnHand
}
def productInstance = new Product(productName: "Some name", productDescription: "Desciption", quantityOnHand: 10)
def propertiesBefore = [:]
productInstance.properties.each { k,v -> propertiesBefore[k] = (v instanceof Cloneable) ? v.clone() : v }
productInstance.productName = "x"
productInstance.productDescription = "y"
productInstance.quantityOnHand = 9
println propertiesBefore.quantityOnHand // this will print the same as the one after the save()
productInstance.save(flush:true)
println propertiesBefore.quantityOnHand // this will print the same as the one above the save()
最佳答案
如果不进行克隆,将散列图 [:] 的值复制到新的散列图 [:] 的空间也可以通过“推”第一个来完成,这将达到您想要的相同结果(按值复制)!
def APE = [:]
APE= [tail: 1, body: "hairy", hungry: "VERY!!!"]
def CAVEMAN = [:]
CAVEMAN << APE //push APE to CAVEMAN's space
//modify APE's values for CAVEMAN
CAVEMAN.tail = 0
CAVEMAN.body = "need clothes"
println "'APE': ${APE}"
println "'CAVEMAN': ${CAVEMAN}"
输出==>
'APE': [tail:1, body:hairy, hungry:VERY!!!]
'CAVEMAN': [tail:0, body:need clothes, hungry:VERY!!!]
关于grails - 按值而不是按引用将对象属性复制到映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25729492/