Groovy 范围 - 如何在方法中访问脚本变量 [英] Groovy scope - how to access script variable in a method
问题描述
我有一个关于 Groovy 中的范围规则的问题.在下面的代码片段中,我有三个变量,a
具有局部作用域,b
具有脚本作用域,c
也应该使用@Field
注释.
I have a question about scoping rules in Groovy. In the following snippet, I have three variables, a
has local scope, b
has script scope, and c
should get script scope as well using the @Field
annotation.
#!/usr/bin/groovy
import groovy.transform.Field;
//println org.codehaus.groovy.runtime.InvokerHelper.getVersion()
def a = 42;
b = "Tea"
@Field def c = "Cheese"
void func()
{
// println a // MissingPropertyException
println b // prints "Tea"
println c // prints "Cheese" with groovy 2.1.2, MissingPropertyException with groovy 1.8.6
}
class Main
{
def method()
{
// println a // MissingPropertyException
// println b // MissingPropertyException
// println c // MissingPropertyException with both 1.8.6. and 2.1.2
}
}
func();
new Main().method();
我在注释指示的行上得到 MissingPropertyException
s.a
上的异常是预期的,因为该变量具有局部作用域.但我希望 b
可以在 method()
内部访问 - 事实并非如此.@Field
在 groovy 1.8.6 中没有做任何事情,虽然升级后它可以工作,所以我猜这是一个老错误.尽管如此,c
在 method()
中的任一版本都无法访问.
I get MissingPropertyException
s on the lines indicated with comments. The exceptions on a
are expected, as that variable has local scope. But I would expect b
to be accessible inside method()
- it isn't.
@Field
doesn't do anything in groovy 1.8.6, although after upgrading it works, so I guess that is an old bug. Nevertheless, c
is inaccessible inside method()
with either version.
所以我的问题是:
- 为什么我不能访问带有
@Field
注释的变量method()
? - 如何在
method()
中引用脚本变量?
- Why can't I access a variable annotated with
@Field
insidemethod()
? - How can I refer to a script variable inside
method()
?
推荐答案
当您在 groovy 脚本中的 class
声明之外有方法或语句时,会创建一个隐式类.回答您的问题:
When you have methods or statements outside of a class
declaration in a groovy script, an implicit class is created. To answer your questions:
在您的示例中,
func()
可以访问字段c
,因为它们都是隐式类的成员.Main
类不是,所以它不能.
In your example,
func()
can access the fieldc
because they are both members of the implicit class. TheMain
class is not, so it can't.
您需要将脚本变量的引用传递给 method()
.一种方法是传递隐式定义的binding
对象,通过它您可以访问所有脚本范围变量.
You need to pass a reference to the script variable to method()
. One way is to pass the implicitly defined binding
object, through which you can access all the script scope variables.
示例:
#!/usr/bin/groovy
import groovy.transform.Field;
//println org.codehaus.groovy.runtime.InvokerHelper.getVersion()
def a = 42;
b = "Tea"
@Field def c = "Cheese"
void func()
{
// println a // MissingPropertyException
println b // prints "Tea"
println c // prints "Cheese" with groovy 2.1.2, MissingPropertyException with groovy 1.8.6
}
class Main
{
def scriptObject
def binding
def method()
{
// println a // MissingPropertyException
println binding.b
println scriptObject.c
}
}
func();
new Main(scriptObject: this, binding: binding).method();
这篇关于Groovy 范围 - 如何在方法中访问脚本变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!