Cloning an object in Groovy (using MOP)


/ Published in: Groovy
Save to your folder(s)

This example shows how to clone an object from an existing one by using MOP in Groovy, first we find all the writable properties of the cloned object class, secondly we traverse them and on each iteration we copy the value from the current object into the newly created one.


Copy this code and paste it in your HTML
  1. class User {
  2.  
  3. def String name
  4. // the list carry on ..
  5.  
  6. def User createNewInstance(){
  7. User.metaClass.getProperties().findAll(){it.getSetter()!=null}.inject(new User()){user,metaProp->
  8. metaProp.setProperty(user,metaProp.getProperty(this))
  9. user
  10. }
  11. }
  12.  
  13. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.