在Groovy中将参数传递方法 [英] Pass method as parameter in Groovy
问题描述
有没有办法在Groovy中将方法作为参数传递,而不将其封装在闭包中?它似乎使用函数,但不是方法。例如,假设如下:
def foo(Closure c){
c(arg1:baz,arg2 :qux)
}
def bar(Map args){
println('arg1:'+ args ['arg1'])
println arg2:'+ args ['arg2'])
}
p>
foo(bar)
但如果 bar
是类中的方法:
class Quux {
def foo(Closure c){
c(arg1:baz,arg2:qux)
}
def bar args){
println('arg1:'+ args ['arg1'])
println('arg2:'+ args ['arg2'])
}
def quuux(){
foo(bar)
}
}
new Quux()。quuux()
无法使用没有此类属性:bar for class:Quux 。
如果我改变方法来封闭闭包中的 bar
,它会工作,但似乎不必要的冗长:
def quuux(){
foo({args - >有没有更清洁的方法? 解决方案 。&
运营商救援!
class Quux {
def foo(Closure c){
c(arg1:baz,arg2:qux)
}
def bar(Map args){
println('arg1:'+ args ['arg1'])
println('arg2:'+ args ['arg2 '])
}
def quuux(){
foo(this& bar)
}
}
$ b b new Quux()。quuux()
// arg1:baz
// arg2:qux
一般来说, obj。& method
会返回一个绑定的方法,例如调用方法
obj
。
Is there a way to pass a method as a parameter in Groovy without wrapping it in a closure? It seems to work with functions, but not methods. For instance, given the following:
def foo(Closure c) {
c(arg1: "baz", arg2:"qux")
}
def bar(Map args) {
println('arg1: ' + args['arg1'])
println('arg2: ' + args['arg2'])
}
This works:
foo(bar)
But if bar
is a method in a class:
class Quux {
def foo(Closure c) {
c(arg1: "baz", arg2:"qux")
}
def bar(Map args) {
println('arg1: ' + args['arg1'])
println('arg2: ' + args['arg2'])
}
def quuux() {
foo(bar)
}
}
new Quux().quuux()
It fails with No such property: bar for class: Quux.
If I change the method to wrap bar
in a closure, it works, but seems unnecessarily verbose:
def quuux() {
foo({ args -> bar(args) })
}
Is there a cleaner way?
解决方案 .&
operator to the rescue!
class Quux {
def foo(Closure c) {
c(arg1: "baz", arg2:"qux")
}
def bar(Map args) {
println('arg1: ' + args['arg1'])
println('arg2: ' + args['arg2'])
}
def quuux() {
foo(this.&bar)
}
}
new Quux().quuux()
// arg1: baz
// arg2: qux
In general, obj.&method
will return a bound method, i.e. a closure that calls method
on obj
.
这篇关于在Groovy中将参数传递方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!