Copying Groovy object properties

I face an issue today where I have to compose a new Groovy object from another existing one. The fact here was that I want to return to caller a summary of this existing object but not the complete object graph (that were GORM objects by the way).

After some research onto Groovy dynamic capabilities, I found what I need with the ExpandoMetaClass. The MetaClass of a GroovyObject is accessible using a metaClass attribute that is automatically added to your object. You can then use this MetaClass to dynamically manipulate properties and methods.

I ended up with the following 3 lines of code, allowing to copy a source object to a target one according the definition provided by target in terms of defined properties.

def target = new TargetObject(){
   if ( != 'metaClass')
      it.setProperty(target, source.metaClass.getProperty(source,

The trick here is not to copy the metaClass property itself !

Who says “Grooovy !” ?

One thought on “Copying Groovy object properties

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s