Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Groovy Closure/Method parameters list

Tags:

grails

groovy

How do we retrieve the list of parameters of a closure/method in groovy dynamically, javascript style through the arguments array

say for example that i want to log a message this way

def closure = {name,id ->
 log.debug "Executing method with params name:${} id:${id}"
}

OR

void method (String name,String id) {
 log.debug "Executing method with params name:${} id:${id}"
}

I read once about a way to reference the list of parameters of a closure, but i have no recollection of that and looking at the groovy API for Closure reveals only getParametersType() method. As for the method, there is a way to call a method as a closure and then i can retrieve the method parameters

ken

like image 458
ken Avatar asked Nov 06 '10 17:11

ken


People also ask

How do I return a Groovy closure?

We can even return closures from methods or other closures. We can use the returned closure to execute the logic from the closure with the explicit call() method or the implicit syntax with just the closure object followed by opening and closing parentheses ( () ).

How closure works in Groovy?

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope.

Does Groovy have named parameters?

Groovy collects all named parameters and puts them in a Map. The Map is passed on to the method as the first argument. The method needs to know how to get the information from the Map and process it.

When you set a value of one parameter it generates a new closure with less than one argument which of the following option relates to the given statement?

Currying in Groovy will let you set the value of one parameter of a closure, and it will return a new closure accepting one less argument.


1 Answers

You won't like it (and I hope it's not my bad to do research and to answer), however:

There is no API to access the list of parameters declared in a Groovy Closure or in a Java Method.

I've also looked at related types, including (for Groovy) MetaClass, and sub-types, and types in the org.codehaus.groovy.reflection package, and (for Java) types in the java.lang.reflect package.

Furthermore, I did an extensive Google search to trace extraterrestrials. ;-)

If we need a variable-length list of closure or method arguments, we can use an Object[] array, a List, or varargs as parameters:

def closure = { id, Object... args ->
    println id
    args.each { println it }
}
closure.call(1, "foo", "bar")

Well, that's the limitations and options!

like image 50
robbbert Avatar answered Sep 24 '22 07:09

robbbert