使用一个或两个参数进行闭包的groovy方法

时间:2012-08-22 16:36:27

标签: groovy closures

我想编写一个方法,将Closure作为参数并传递给它两个参数,但编写该闭包的人可以指定一个或两个参数,因为他喜欢

我试过这样的方式:

def method(Closure c){
     def firstValue = 'a'
     def secondValue = 'b'
     c(firstValue, secondValue);
}

//execute
method { a ->
   println "I just need $a"
}
method { a, b ->
   println "I need both $a and $b"
}

如果我尝试执行此代码,结果为:

Caught: groovy.lang.MissingMethodException: No signature of method: clos2$_run_closure1.call() is applicable for argument types: (java.lang.String, java.lang.String) values: [a, b]
Possible solutions: any(), any(), dump(), dump(), doCall(java.lang.Object), any(groovy.lang.Closure)
    at clos2.method(clos2.groovy:4)
    at clos2.run(clos2.groovy:11)

我该怎么做?

2 个答案:

答案 0 :(得分:28)

你可以在调用之前询问Closure的maximumNumberOfParameters

def method(Closure c){
    def firstValue = 'a'
    def secondValue = 'b'
    if (c.maximumNumberOfParameters == 1)
        c(firstValue)
    else
        c(firstValue, secondValue)
}

//execute
method { a ->
    println "I just need $a"
}
method { a, b ->
    println "I need both $a and $b"
}

输出:

I just need a
I need both a and b

答案 1 :(得分:3)

最简单的是给它一个默认值:

method { a, b=nil ->
   println "I just need $a"
}

您也可以使用数组:

method { Object[] a ->
  println "I just need $a"
}