Last Updated: February 25, 2016
·
612
· patthegamer

Groovy DSL: Setting properties like functions

Recently I wanted to be able to set properties on an object in a closure without having to use the = operator.

This is what I didn't want to do:


closure = {
    foo = "abc"
    bar = "efg"
}

This is what I actually wanted to do:

closure = {
    foo "abc"
    bar "efg"  
}

To do this I implemented the methodMissing function, saw if that object had the property, and if it does, sets that property.

class MyClosure {
    def foo
    def bar

    def methodMissing(String name, args) {
        if(this.properties.containsKey(name)) {
            setProperty(name,args)
        }
    }
}

closure = {
    foo "abc"
    bar "efg"
}

myClosure = new MyClosure()
closure.delegate = myClosure
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure()
myClosure.properties.each{key,value-> println key + ": " + value}