Posted By

narkisr on 09/18/08


Tagged

groovy MOP Cloning


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

doctorillo
sfhynx
laurenceosx


Cloning an object in Groovy (using MOP)


 / Published in: Groovy
 

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.

  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  

You need to login to post a comment.