Skip to content

Instantly share code, notes, and snippets.

@hgmiguel
Created November 11, 2014 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hgmiguel/6626cb0162715d0eaa71 to your computer and use it in GitHub Desktop.
Save hgmiguel/6626cb0162715d0eaa71 to your computer and use it in GitHub Desktop.
Ejemplo de invocacion dinamica de metodos en groovy
class DemoDynamic {
Map<String, List<String>> permissions = [:]
Boolean hasPermission(String name, String permission){
permission in permissions?."$name"
}
Map createPermission(String name, List<String> permissions) {
this.permissions?."$name" = permissions
this.permissions
}
def dynamicMethods = [[regex:"hasPermission(.*)", method:this.&hasPermission],
[regex:"create(.*)Permission", method:this.&createPermission]]
def methodMissing(String name, args) {
def method = dynamicMethods.find { name =~ it.regex}
if(method) {
def match = name =~ method.regex
return method.method(match[0][1], * args)
} else
throw new MissingMethodException(name, DemoDynamic , args)
}
}
demo = new DemoDynamic()
demo.createHgmiguelPermission(["write","read"])
demo.createOtrosPermission(["read"])
assert demo.hasPermissionHgmiguel("write")
assert !demo.hasPermissionOtros("write")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment