【问题标题】:Can't pass closures in groovy不能在 groovy 中通过闭包
【发布时间】:2012-03-31 08:57:40
【问题描述】:

我正在尝试为 Geb 库 (http://www.gebish.org/manual/current/intro.html#introduction) 运行一个基本示例。代码如下:

import geb.Browser

Browser.drive {
   go "http://google.com/ncr"

    // make sure we actually got to the page
    assert title == "Google"

    // enter wikipedia into the search field
    $("input", name: "q").value("wikipedia")

    // wait for the change to results page to happen
    // (google updates the page dynamically without a new request)
    waitFor { title.endsWith("Google Search") }

    // is the first link to wikipedia?
    def firstLink = $("li.g", 0).find("a.l")
    assert firstLink.text() == "Wikipedia"

    // click the link 
    firstLink.click()

    // wait for Google's javascript to redirect to Wikipedia
    waitFor { title == "Wikipedia" }
}

当我尝试运行它时(使用 Eclipse 的 groovy 支持),我得到以下异常:

Caught: groovy.lang.MissingMethodException: No signature of method: static geb.Browser.drive() is applicable for argument types: (ExampleScript$_run_closure1) values: [ExampleScript$_run_closure1@2a62610b]
Possible solutions: drive(groovy.lang.Closure), drive(geb.Browser, groovy.lang.Closure), drive(geb.Configuration, groovy.lang.Closure), drive(java.util.Map, groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter)
groovy.lang.MissingMethodException: No signature of method: static geb.Browser.drive() is applicable for argument types: (ExampleScript$_run_closure1) values: [ExampleScript$_run_closure1@2a62610b]
Possible solutions: drive(groovy.lang.Closure), drive(geb.Browser, groovy.lang.Closure), drive(geb.Configuration, groovy.lang.Closure), drive(java.util.Map, groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter)
at ExampleScript.run(ExampleScript.groovy:21)

我认为这是说我传递给静态 Browser.drive 方法的闭包类型与 groovy.lang.Closure 不兼容,但我不知道为什么。简单的 groovy hello world 脚本可以正常工作,但将闭包传递给方法总是会返回类似的错误。

【问题讨论】:

  • 如果你在 Eclipse 之外运行它会起作用吗?看起来 Eclipse 给你的类加载器问题...
  • 似乎是 Eclipse 配置。 Groovy Eclipse 生成了一个使用 GroovyStarter 的启动配置。在命令行上直接调用 java 成功后,我将启动配置更改为直接调用我的脚本,它工作正常。 GroovyStarter 是否可以正常工作?如果脚本编译成带有 main 方法的类,GroovyStarter 的目的是什么?

标签: groovy closures geb


【解决方案1】:

抄袭自:http://groovy.codehaus.org/Differences+from+Java

Java 程序员习惯于用分号结束语句并且没有闭包。类定义中还有实例初始化器。所以你可能会看到类似的东西:

class Trial {
  private final Thing thing = new Thing ( ) ;
  { thing.doSomething ( ) ; }
}

许多 Groovy 程序员避免使用分号,因为分号会分散注意力和多余(尽管其他人一直使用它们 - 这是编码风格的问题)。导致困难的情况是在 Groovy 中将上述内容编写为:

class Trial {
  private final thing = new Thing ( )
  { thing.doSomething ( ) }
}

这将引发 MissingMethodException!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多