Copying Groovy object properties – back and forth

I’ve blogged some weeks ago about copying Groovy object properties and comes back today with a complementary post.

Just to remember the context and set ideas, here’s the problem : you want to make a copy of an object graph by selecting only the properties/objects you need with now the constraint that the copy mechanism should be working back and forth. The 2 classes below can be used to illustrate this.

User can represent any domain classes (typically a GORM object into a Grails application). In this exemple, User has blog posts and belongs to a company.

class User{
   String login
   String firstname
   String lastname
   Date registrationDate
   static hasMany = [posts: Post]
   static belongsTo = [company: Organization]

UserView represents the lightweight view that one want to extract from domain model. We just want the login and the company.

class UserView{
   String login
   Organization company

The code presented in previous post has the drawback that it only worked in one way : when copying User properties into UserView. When used the reverse way, it failed because properties – such as firstname for example – defined in UserView do not exist into User. After some refactoring of previous code, I ended up with the following util method based on dynamic Groovy documentation :

def copyProperties(def source, def target){{
      if (source.metaClass.hasProperty(source, && != 'metaClass' && != 'class')
         it.setProperty(target, source.metaClass.getProperty(source,

The trick here is to check that source class just have the current property before trying to set it. And this method can now be used back and forth like this :

def user = User.findByLogin('lbroudoux')
def view = new UserView()
copyProperties(user, view)
assert view.login == 'lbroudoux'
view.login = 'changeme'
copyProperties(view, user)
assert user.login == 'changeme'

Once again, Groovy let’s make easy the thing that may be complicated in Java !


One thought on “Copying Groovy object properties – back and forth

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