title: Copy Groovy class properties
body: <p>I want to <strong>copy object properties to another object</strong> in a generic way (if a property exists on target object, I copy it from the source object).</p>
  
  <p>My code works fine using <a href="http://groovy.codehaus.org/gapi/groovy/lang/ExpandoMetaClass.html" rel="noreferrer">ExpandoMetaClass</a>, but I don't like the solution. Are there any other ways to do this? </p>
  
  <pre><code>class User {
      String name = 'Arturo'
      String city = 'Madrid'
      Integer age = 27
  }
  
  class AdminUser {
      String name
      String city
      Integer age
  }
  
  def copyProperties(source, target) {
      target.properties.each { key, value -&gt;
          if (source.metaClass.hasProperty(source, key) &amp;&amp; key != 'class' &amp;&amp; key != 'metaClass') {
              target.setProperty(key, source.metaClass.getProperty(source, key))
          }
      }
  }
  
  def (user, adminUser) = [new User(), new AdminUser()]
  assert adminUser.name == null
  assert adminUser.city == null
  assert adminUser.age == null
  
  copyProperties(user, adminUser)
  assert adminUser.name == 'Arturo'
  assert adminUser.city == 'Madrid'
  assert adminUser.age == 27
  </code></pre>