revember use the closure clone:
1 )
class Product {
String imgUrl
}
def p = new Product(imgUrl: "test1")
def p1
p1 = {p}.clone()
p1.imgUrl="test2"
println "--"+p1.imgUrl
println p.imgUrl
2 )
class Product {
String name
String imgUrl
}
def p = new Product(name:"1", imgUrl: "test1")
def p1 = new Product(name:"2", imgUrl: "test2")
def result = []
result <<p
result <<p1
def result2 = []
def test
result.each{
test = {it}.clone()
result2 << test
}
test.imgUrl ="KKKKKK"
println "-------------------"+test.imgUrl
//def result2 = {[*result]}.clone()
result2.each {
it.imgUrl = it.name+"KK"
}
result2.each {
println "-----"+it.imgUrl
println "-----"+it.name
}
result.each {
println "*****"+it.imgUrl
println "*name*"+it.name
}
本文通过两个Groovy代码示例展示了如何使用闭包进行对象克隆,并演示了克隆后的对象属性修改过程。第一个示例涉及单一对象的克隆,而第二个示例则展示了如何对对象列表进行克隆及后续操作。
669

被折叠的 条评论
为什么被折叠?



