Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables 如何在Groovy脚本引擎中使用局部作用域变量?_Variables_Groovy_Scope_Global_Local - Fatal编程技术网

Variables 如何在Groovy脚本引擎中使用局部作用域变量?

Variables 如何在Groovy脚本引擎中使用局部作用域变量?,variables,groovy,scope,global,local,Variables,Groovy,Scope,Global,Local,在我在groovy脚本引擎上运行的groovy脚本中,所有变量似乎都是全局变量。我创建了一些groovy类,但当我创建变量时,它们可以从任何地方访问。例如 class test{ void func1{ a=4 } void func2{ print(a) } } 当我从scala调用这个类函数func1,然后调用func2时,结果是“4”。奇怪的是,如果我在函数中声明像“defa=0”这样的变量,变量的作用域将受到函数中的限制 我正在从GroovyScriptEngine加载groo

在我在groovy脚本引擎上运行的groovy脚本中,所有变量似乎都是全局变量。我创建了一些groovy类,但当我创建变量时,它们可以从任何地方访问。例如

class test{
  void func1{ a=4 }
  void func2{ print(a) }
}
当我从scala调用这个类函数func1,然后调用func2时,结果是“4”。奇怪的是,如果我在函数中声明像“defa=0”这样的变量,变量的作用域将受到函数中的限制

我正在从GroovyScriptEngine加载groovy脚本,如下所示(使用scala)


然后使用invokeMethod调用groove脚本类中的函数。在默认情况下,是否存在使变量作用域受限于in函数的方法?

这是预期的行为,如中所述

在Groovy脚本中使用未声明的变量会创建绑定变量。绑定变量是脚本的全局变量。如果使用
def
声明变量,它将成为函数局部变量

此行为仅适用于作为脚本加载代码的情况。我认为不可能改变它。当需要局部变量时,只需使用声明(
def
或类型)

请注意,还可以使用@Field注释定义绑定变量(全局):

class test {
  void func1{ @Field int a=4 }
  void func2{ print(a) }
}
相当于

class test {
  void func1{ a=4 }
  void func2{ print(a) }
}

谢谢,这让我很烦恼
class test {
  void func1{ a=4 }
  void func2{ print(a) }
}