Wednesday, July 03, 2013

Groovy Dynamic code

This is fairly old, but still cool, and I just had a need to use it today, so I thought I'd post about it.

My problem was I wanted to mock out a Domain class. If a proerty value was null., then I wanted to create a mock value for that property. IF the property had a value, then I wanted to return that.

Using Dynamic programming this was easy.

class A{
  def doit(){
        println "doing..";
    }
    String var="yoyo";
}

def a = new A();

a.metaClass.getProperty = {p ->
    def meta = a.metaClass.getMetaProperty(p)
    if(meta){
        def mp = meta.getProperty(delegate)
        if(mp)
            return mp
    }
    return "DynoGet${p}"
}

println a.var
println a.mar
a.var=null
println a.var


Output

 
yoyo
DynoGetmar
DynoGetvar

The key here is the metaClass.getMetaProperty, and the meta.getProperty(delegate). They check if the property exists, first, and then if it has a value assigned. If not then I create a default value.



No comments: