Skip to content

Instantly share code, notes, and snippets.

@dmitric
Created September 28, 2011 16:04
Show Gist options
  • Save dmitric/1248339 to your computer and use it in GitHub Desktop.
Save dmitric/1248339 to your computer and use it in GitHub Desktop.
MapBackedBean
class MapBackedBean implements GroovyInterceptable {
private Map map = [:]
def invokeMethod(String name, args){
if (name == "putAt"){
map[args[0]] = args[1]
} else if (name == "getAt"){
return map[args[0]]
} else if (args.size() > 1 || name.length() <= 3){
throw new RuntimeException("This bean object only allows at most one argument to a method, and getters and setters")
} else {
String propertyName = name[3].toLowerCase()+ name.substring(4)
if(name.startsWith("set")){
map[propertyName]= args[0]
} else if (name.startsWith("get") && args.size() == 0){
if (map.containsKey(propertyName)){
return map[propertyName]
}else{
throw new groovy.lang.MissingMethodException("No such method ${name}", super.class, args)
}
} else {
throw new groovy.lang.MissingMethodException("No such method ${name}", super.class, args)
}
}
}
def getProperty(String propertyName){
propertyName = propertyName[0].toLowerCase()+propertyName.substring(1)
if (map.containsKey(propertyName)){
return map[propertyName]
} else {
throw new groovy.lang.MissingPropertyException("No such property: ${propertyName} for class: ${super.getClass()}")
}
}
public void setProperty(String propertyName, Object newValue){
map[propertyName[0].toLowerCase()+propertyName.substring(1)] = newValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment