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

查看:3036
本文介绍了如何在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天全站免登陆