如何在Groovy中创建和访问全局变量?

sri*_*ini 112 groovy

我需要在一个方法中将值存储在变量中,然后我需要在另一个方法或闭包中使用该变量中的值.我该如何分享这个价值?

小智 184

在Groovy脚本中,范围可能与预期不同.这是因为Groovy脚本本身就是一个带有运行代码的方法的类,但这一切都是在运行时完成的.我们可以通过省略类型定义来定义要限定脚本的变量,或者在Groovy 1.8中我们可以添加@Field注释.

import groovy.transform.Field

var1 = 'var1'
@Field String var2 = 'var2'
def var3 = 'var3'

void printVars() {
    println var1
    println var2
    println var3 // This won't work, because not in script scope.
}
Run Code Online (Sandbox Code Playgroud)

  • 只需注意Field @requires import .. import groovy.transform.Field (29认同)
  • 我使用Groovy在Jenkins管道中尝试了`var1 ='var1'`方法,但是它不起作用。我不得不使用@Field var1 ='var1' (4认同)

Bob*_*ann 47

class Globals {
   static String ouch = "I'm global.."
}

println Globals.ouch
Run Code Online (Sandbox Code Playgroud)


Gau*_*ana 20

def iamnotglobal=100 // This will not be accessible inside the function

iamglobal=200 // this is global and will be even available inside the 

def func()
{
    log.info "My value is 200. Here you see " + iamglobal
    iamglobal=400
    //log.info "if you uncomment me you will get error. Since iamnotglobal cant be printed here " + iamnotglobal
}
def func2()
{
   log.info "My value was changed inside func to 400 . Here it is = " + iamglobal
}
func()
func2()
Run Code Online (Sandbox Code Playgroud)

这里iamglobal变量是func使用的全局变量,然后再次可用于func2

如果你使用def声明变量,它将是本地的,如果你不使用def它的全局


Aar*_*lla 5

与所有 OO 语言一样,Groovy 本身没有“全局”的概念(与 BASIC、Python 或 Perl 不同)。

如果您有多个方法需要共享同一个变量,请使用一个字段:

class Foo {
    def a;

    def foo() {
        a = 1;
    }
    def bar() {
        print a;
    }
}
Run Code Online (Sandbox Code Playgroud)


tim*_*tes 1

只需在类或脚本范围内声明变量,然后从方法或闭包内部访问它。如果没有示例,就很难更具体地解决您的特定问题。

然而,全局变量通常被认为是不好的形式。

为什么不从一个函数返回变量,然后将其传递到下一个函数?