grails - 按值而不是按引用将对象属性复制到映射

标签 grails groovy

我不确定我哪里出错了,但似乎我无法从对象实例复制属性并将它们分配给 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/

相关文章:

scripting - 从脚本数据源访问 Pentaho 中的参数?

unit-testing - 如何在带有模拟域的grails单元测试中测试默认排序

grails - Grails-多对多数据持久性(已编辑)

java - 如何在 Spring Boot 2.0.5 应用程序上启用 HTTPS

android - 将数据从 settings.gradle 传递到 build.gradle

java - 从 mule esb 向主程序传递参数

java - 删除常规中字段的第一个字符

json - 从 Grails RestfulController 索引/搜索操作渲染分页元数据

java - 创建名称为 'mongoTransactionManager'的bean时出错:在设置bean属性 'mongoDatastore'时无法解析对bean 'datastore'的引用

grails:在开发中向嵌入式 tomcat 添加上下文