title: Copy Object Properties to a Map by Value not by Reference
body: <p>I'm not sure where i'm going wrong, but it seems that I'm not able to copy properties from an object instance and assign them to a map without the values being changed after saving the instance.</p>
  
  <p>This is a sample class:</p>
  
  <pre><code>class Product {
      String productName
      String proudctDescription
      int quantityOnHand
  }
  </code></pre>
  
  <p>Once the form is submitted and it's sent to my controller, I can access the values and manipulate them from the <code>productInstance.properties</code> map that is available from the instance. I want to copy the properties to another map to preserve the values before committing them during an edit. So let's say we are editing a record and these are the values stored in the db: <code>productName = "My Product"</code>, <code>productDescription = "My Product Description"</code> and <code>quantityOnHand = 100</code>. </p>
  
  <p>I want to copy them to:</p>
  
  <pre><code>def propertiesBefore = productInstance.properties
  </code></pre>
  
  <p>This did not work, because when I save the productInstance, the values in propertiesBefore change to whatever the instance had.</p>
  
  <p>So I tried this:</p>
  
  <pre><code>productInstance.properties.each { k,v -&gt; propertiesBefore[k] = v }
  </code></pre>
  
  <p>Same thing happened again. I am not sure how to copy by value, it seems no matter what I try it copies by reference instead.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>As per the request of Pawel P., this is the code that I tested:</p>
  
  <pre><code>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 -&gt; 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()
  </code></pre>