【发布时间】:2014-09-08 17:08:10
【问题描述】:
我不确定我哪里出错了,但似乎我无法从对象实例复制属性并将它们分配给地图,而在保存实例后不更改值。
这是一个示例类:
class Product {
String productName
String proudctDescription
int quantityOnHand
}
提交表单并将其发送到我的控制器后,我可以从实例中可用的productInstance.properties 映射访问这些值并对其进行操作。我想将属性复制到另一个地图以在编辑期间提交它们之前保留这些值。假设我们正在编辑一条记录,这些是存储在数据库中的值:productName = "My Product"、productDescription = "My Product Description" 和quantityOnHand = 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()
【问题讨论】: