Skip to content

Instantly share code, notes, and snippets.

@darylteo
Last active August 29, 2015 14:05
Show Gist options
  • Save darylteo/fbdc989f91c18394aaa8 to your computer and use it in GitHub Desktop.
Save darylteo/fbdc989f91c18394aaa8 to your computer and use it in GitHub Desktop.
A Map + Expando implementation for Groovy
import groovy.json.*;
class MyBean extends Expando {
def methodMissing(String name, def args) {
if(args.size() == 0) {
super.getProperty(name)
} else if(args.size() == 1) {
def value = args[0];
def result = value;
if(value instanceof Closure) {
result = new MyBean();
value.delegate = result;
value.resolveStrategy = Closure.DELEGATE_FIRST;
value.call(result);
}
super.setProperty(name, result);
} else {
throw new MissingMethodException(name, MyBean.class, args)
}
}
def toMap() {
return this.getProperties();
}
}
def bean = new MyBean();
println bean.foo
bean.foo = "Bar"
println bean.foo
println bean.foo()
bean.foo("Hello")
println bean.foo
println bean.foo()
bean.foo {
hello 'World'
}
bean.foo.bar = "Hey"
println bean.foo
bean.foo.hello = "Blah!"
println bean
println bean.toMap()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment