【问题标题】:Groovy - A Tale of Two Closure InvocationsGroovy - 两个闭包调用的故事
【发布时间】:2013-07-25 10:59:39
【问题描述】:

这行得通:

def myClosure = { println 'Hello world!' }
'myClosure'()

这不起作用:

def myClosure = { println 'Hello world!' }
String test = 'myClosure'
test()

为什么,有没有办法?

【问题讨论】:

    标签: string groovy closures


    【解决方案1】:

    test()
    

    解析器会将其评估为对 test 闭包/方法的调用,而不首先将其评估为变量(否则您无法调用任何具有同名变量的方法)

    请尝试:

    myClosure = { println 'Hello world!' }
    String test = 'myClosure'
    "$test"()
    

    编辑——类示例

    class Test {
      def myClosure = { println "Hello World" }
    
      void run( String closureName ) {
        "$closureName"()
      }
    
      static main( args ) {
        new Test().run( 'myClosure' )
      }
    }
    

    Edit -- 带有运行闭包示例的类

    class Test {
      def myClosure = { println "Hello World" }
    
      def run = { String closureName ->
        "$closureName"()
      }
    
      static main( args ) {
        new Test().run( 'myClosure' )
      }
    }
    

    【讨论】:

    • "Caught: groovy.lang.MissingMethodException: No signature of method: Test.myclosure() is applicable for argument types: () values: []" 我还发现单引号 (' $test'()) 甚至没有那么远。
    • @RandomHuman 单引号不会生成模板化的 GroovyString,(它将尝试运行名为 $test 的闭包)。当您在纯脚本中运行它时,您是否像我在上面的代码中那样从 Closure 定义中删除了 def
    • 删除def 似乎确实使它工作......在一个简单的脚本中。但是我只设置了其中一个来拥有一个独立的示例。实际上,所有这些都存在于class 中。我发现将def 放入class 的结果很糟糕。
    • 好的,经过一些实验,我想我已经找出了我的问题所在。在我的Test 类中,我的run() 本身就是一个闭包(而不是一个方法,就像你在这里一样)。这似乎不起作用。
    • @RandomHuman 添加了另一个示例,其中run 是一个闭包,它似乎也可以工作......
    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多