本文介绍了Groovy方法无法访问封闭范围内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是闭包的用途,但是以下内容也不能正常工作吗?:

I know that this is what closures are for, but shouldn't the below work as well?:

def f = 'foo'
def foo() {
   println(f)
}
foo()

结果为:

Caught: groovy.lang.MissingPropertyException: No such property: f for class: bar
groovy.lang.MissingPropertyException: No such property: f for class: bar
   at bar.foo(bar.groovy:4)
   at bar.run(bar.groovy:7)

推荐答案

在groovy脚本(与类相对)中,您的代码实质上等效于:

In a groovy script (as opposed to class), your code is essentially equivalent to:

class ScriptName {
  def main(args) {
    new ScriptName().run(args)
  }

  def run(args) {
    def f = 'foo'
    foo()
  }

  def foo() {
    println(f)
  }
}

由groovy为groovy脚本创建的隐式"封闭类始终存在,但在您的代码中不可见.上面说明了为什么foo方法看不到f变量的原因.

the 'implicit' enclosing class created by groovy for groovy scripts is always present but not visible in your code. The above makes it obvious why the foo method does not see the f variable.

您有两种选择

选项1-绑定

有关详细信息,请参见有关脚本绑定的常规文档.

See the groovy docs on script bindings for details.

// put the variable in the script binding
f = 'foo'

这是以下简称:

binding.setVariable('f', 'foo')

groovy脚本的脚本绑定随处可见,这使得变量本质上是"global".

where the script binding is visible everywhere for groovy scripts and this makes the variable essentially 'global'.

选项2-@Field批注

有关详细信息,请参见关于字段"批注的常规文档.

See groovy docs on the Field annotation for details.

import groovy.transform.Field
...
// use the groovy.transform.Field annotation
@Field f = 'foo'

Field注释专门用于使groovy脚本能够将字段添加到隐式"封闭类中.然后,生成的类将类似于以下内容:

the Field annotation is specifically there to give groovy scripts the ability to add fields to the 'implicit' enclosing class. The generated class would then look something like the following:

class ScriptName {
  def f = 'foo'

  def main(args) {
    new ScriptName().run(args)
  }

  def run(args) {
    foo()
  }

  def foo() {
    println(f)
  }
}

从本质上讲也使变量可以在脚本中全局"访问.

which also essentially makes the variable accessible 'globally' in the script.

这篇关于Groovy方法无法访问封闭范围内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:19