如何在 Groovy 中创建和访问全局变量? [英] How do I create and access the global variables in Groovy?

查看:27
本文介绍了如何在 Groovy 中创建和访问全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to store a value in a variable in one method and then I need to use that value from that variable in another method or closure. How can I share this value?

推荐答案

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

In a Groovy script the scoping can be different than expected. That is because a Groovy script in itself is a class with a method that will run the code, but that is all done runtime. We can define a variable to be scoped to the script by either omitting the type definition or in Groovy 1.8 we can add the @Field annotation.

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.
}

这篇关于如何在 Groovy 中创建和访问全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆