Created
February 28, 2014 19:49
-
-
Save andresteingress/9278441 to your computer and use it in GitHub Desktop.
Groovy - Getting Closure Shared Variable Names
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
// convert a method name to a variable name (remove ‘get’ and uncapitalize) | |
def toVariableName = { String methodName -> | |
if (!methodName || !methodName.startsWith('get')) return methodName | |
def variableName = methodName - 'get' | |
return "" + Character.toLowerCase(variableName.charAt(0)) + variableName.substring(1); | |
} | |
// some closure shared variables | |
def x = 42 | |
def m = [1,2,3,4] | |
def c = { | |
println x | |
m.each { println it } | |
} | |
// get all declared getter methods and convert their names to variable names | |
def getters = c.class.declaredMethods.findAll { it.name.startsWith 'get' }*.name // get all the getter methods from the Closure descendant only | |
assert ['m', 'x'] == getters.collect { toVariableName(it) } // convert them to variable names |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment