Wednesday, March 2, 2011

Generating clone/mapping code

If you find yourself typing manually boring mapping code, there is something wrong.

Either install an Eclipse plugin to generate the code for you,
or use Dozer,
or write a script to generate the code for you.

Here is a simple example of such a script (it's Groovy but it's basically Java)

package com.pierre

import java.lang.reflect.Method

class CloneGenerator {

 static main(args) {
  Class clazz = Class.forName("com.acme.mypackage.MyClass")
  for (Method m : clazz.getMethods()) {
   if (m.getName().startsWith("get")) {
    String attribute = m.getName().substring(3); 
    println("objectDestination.set" + attribute + "(objectSource.get" + attribute + "());")
   }
  }
 }

}



No comments: