使用一个或两个参数进行闭包的groovy方法
我想写一个方法,将闭包作为参数传递给它两个参数,但是编写闭包的人可以根据自己的喜好指定一个或两个参数 我试着这样做:使用一个或两个参数进行闭包的groovy方法,groovy,closures,Groovy,Closures,我想写一个方法,将闭包作为参数传递给它两个参数,但是编写闭包的人可以根据自己的喜好指定一个或两个参数 我试着这样做: def method(Closure c){ def firstValue = 'a' def secondValue = 'b' c(firstValue, secondValue); } //execute method { a -> println "I just need $a" } method { a, b ->
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)
如何操作?最简单的方法是给它一个默认值:
method { a, b=nil ->
println "I just need $a"
}
您还可以使用阵列:
method { Object[] a ->
println "I just need $a"
}
在调用之前,您可以询问关闭的时间:
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"
}
输出:
我只需要一个
我需要a和b
No,我也可以声明它,并确保b将有一个值,问题是我不想在编写闭包时声明它。我想改变的是方法,而不是方法closures@rascio你不能不跳圈就做到这一点。您可以检查闭包的parameterTypes
length,看看它需要多少参数,我想,并正确地调用它。但是你要特别地调用一个传递n个参数的闭包,除非你做了一些神奇和可怕的事情,否则闭包需要接受它们。