【问题标题】:groovy.lang.MissingMethodException while trying to pass a closure as a parametergroovy.lang.MissingMethodException 尝试将闭包作为参数传递
【发布时间】:2016-06-26 13:57:10
【问题描述】:

我是 groovy 的新手,正在尝试将闭包作为参数传递给方法,下面是我的代码,我使用的是 Groovy 2.4

class Test
{
    def testMethod()
    {
        def cl = {a,b -> println "a = "+${a}+" b = "+${b}}
        testClosure(cl);
    }

    def testClosure(closure)
    {
        closure(5,2);
    }
}

我在尝试执行时遇到以下异常,

Caught: groovy.lang.MissingMethodException: No signature of method: 
   com.gr.practice.Test.$() is applicable for argument types:
   (com.gr.practice.Test$_testMethod_closure1$_closure2) values:
   [com.gr.practice.Test$_testMethod_closure1$_closure2@3e92efc3]
Possible solutions: 
   is(java.lang.Object), 
   any(),
   any(groovy.lang.Closure),
   use([Ljava.lang.Object;),
   wait(), 
   dump()
groovy.lang.MissingMethodException: No signature of method:
   com.gr.practice.Test.$() is applicable for argument types:
   (com.gr.practice.Test$_testMethod_closure1$_closure2) values:
   [com.gr.practice.Test$_testMethod_closure1$_closure2@3e92efc3]
Possible solutions: 
   is(java.lang.Object),
   any(),
   any(groovy.lang.Closure),
   use([Ljava.lang.Object;),
   wait(),
   dump()
    at com.gr.practice.Test$_testMethod_closure1.doCall(Test.groovy:10)
    at com.gr.practice.Test.testClosure(Test.groovy:16)
    at com.gr.practice.Test$testClosure$0.callCurrent(Unknown Source)
    at com.gr.practice.Test.testMethod(Test.groovy:11)
    at com.gr.practice.Test$testMethod.call(Unknown Source)
    at com.gr.practice.main.run(main.groovy:7)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

有人可以帮忙吗?

【问题讨论】:

  • 嗨,您可以将其标记为已修复,问题是我的 ${variable} 应该在引号内。
  • @DanielA.Thompson 我不认为这与您提到的问题重复。这是两个不同的问题。

标签: groovy


【解决方案1】:

您的问题是println "a = "+${a}+" b = "+${b}。你可能想要这个:

println "a = ${a} b = ${b}"

或者:

println "a = " + a + " b = " + b

(前者更好)

【讨论】:

  • 感谢您的回复 Jeff ,虽然在 Intellig Idea 中做了同样的修复,但在 eclipse 中使用 groovy-eclipse 插件遇到了同样的问题,下面是即兴代码,def static main(String[] args) { def cl = { a,b -> println "a = ${a} and b = ${b}"} testClosure(cl) } private def testClosure(closure) { closure(5,2) }你有线索吗为什么会发生这种情况?
  • println "a = ${a} b = ${b}" 是有效的 Groovy 代码,无论您使用什么 IDE。如果 IDE 出于某种原因抱怨它,那就是 IDE 错误。这是有效的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多