12

我想编写一个将闭包作为参数并将两个参数传递给它的方法,但是编写该闭包的人可以根据自己的喜好指定一个或两个参数

我试过这样:

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)

我该怎么做?

4

2 回答 2

31

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
于 2012-08-22T17:16:37.637 回答
3

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

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

您还可以使用数组:

method { Object[] a ->
  println "I just need $a"
}
于 2012-08-22T16:39:00.327 回答