Skip to content

Instantly share code, notes, and snippets.

@andresteingress
Created February 28, 2014 19:49
Show Gist options
  • Save andresteingress/9278441 to your computer and use it in GitHub Desktop.
Save andresteingress/9278441 to your computer and use it in GitHub Desktop.
Groovy - Getting Closure Shared Variable Names
// 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