Created
November 11, 2014 03:14
-
-
Save hgmiguel/6626cb0162715d0eaa71 to your computer and use it in GitHub Desktop.
Ejemplo de invocacion dinamica de metodos en groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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