按值而非引用将对象属性复制到映射

2024-01-03

我不确定哪里出了问题,但似乎我无法从对象实例复制属性并将它们分配给映射,而在保存实例后不更改值。

这是一个示例类:

class Product {
    String productName
    String proudctDescription
    int quantityOnHand
}

提交表单并将其发送到我的控制器后,我可以访问这些值并从productInstance.properties从实例中可用的地图。我想将属性复制到另一个地图以在编辑期间提交它们之前保留这些值。假设我们正在编辑一条记录,这些是存储在数据库中的值:productName = "My Product", productDescription = "My Product Description" and quantityOnHand = 100.

我想将它们复制到:

def propertiesBefore = productInstance.properties

这不起作用,因为当我保存 ProductInstance 时,属性 Before 中的值更改为实例所具有的值。

所以我尝试了这个:

productInstance.properties.each { k,v -> propertiesBefore[k] = v }

同样的事情又发生了。我不确定如何按值复制,似乎无论我尝试什么,它都会按引用复制。

EDIT

根据 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()

如果不进行克隆,也可以通过“推”第一个值来将 hash-map [:] 的值复制到新的 hash-map [:] 的空间中,这将达到您想要的相同结果(复制价值)!

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!!!]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按值而非引用将对象属性复制到映射 的相关文章

随机推荐