【问题标题】:groovy method that take closure with one or two arguments用一个或两个参数关闭的 groovy 方法
【发布时间】:2012-08-18 03:24:40
【问题描述】:

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

我是这样尝试的:

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)

我该怎么做?

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    你可以在调用之前询问闭包的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
    

    【讨论】:

      【解决方案2】:

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

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

      你也可以使用数组:

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

      【讨论】:

      • 不,我也可以声明它并确保 b 会有一个值,问题是我不想在编写闭包时声明它。我想改变的是方法而不是闭包
      • @rascio 如果不跳过箍,您将无法做到这一点。你可以检查闭包的parameterTypes 长度,看看它需要多少参数,我想,并正确调用它。但是你专门调用了一个传递 n 参数的闭包,除非你做了一些神奇和可怕的事情,否则闭包需要接受它们。
      猜你喜欢
      • 2014-08-07
      • 2014-03-17
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多