Sunday, 27 January 2019

Groovy: closure.getParameterTypes().size(): Check number of arguments this closure takes


‘closure.getParameterTypes().size()’ return number of arguments supplied to the closure.

HelloWorld.groovy
def performAction(Closure closure){
 int size = closure.getParameterTypes().size()
 
 if(size == 1){
  println "Closure takes one argument"
 }else if(size == 2){
  println "Closure takes two arguments"
 }else{
  println "Closure takes more than two arguments"
 }
}

performAction {x -> x * x}
performAction {x, y -> x + y}
performAction {x, y, z -> x + y + z}

Output
Closure takes one argument
Closure takes two arguments
Closure takes more than two arguments



Previous                                                 Next                                                 Home

No comments:

Post a Comment