加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy:如何从groovy脚本中的方法设置属性/字段/ def?

发布时间:2020-12-14 16:20:44 所属栏目:大数据 来源:网络整理
导读:题 给定一个简单的groovy脚本(不是类!),如何设置方法外的属性/字段的值? 例 以下代码无法按预期工作: def hi;def setMyVariable() { hi = "hello world!"}setMyVariable()assert hi == "hello world!" //failsprintln hi //prints null 尝试失败 我尝试过

给定一个简单的groovy脚本(不是类!),如何设置方法外的属性/字段的值?

以下代码无法按预期工作:

def hi;

def setMyVariable() {
    hi = "hello world!"
}

setMyVariable()
assert hi == "hello world!"    //fails
println hi                     //prints null

尝试失败

我尝试过很多东西,包括以下内容,都失败了

def setMyVariable() {
    this.hi = "hello world!"
}

public void setMyVariable() {
    hi = "hello world!"
}

public String hi;
public void setMyVariable() {
    this.hi = "hello world!";
}

摘要

设置方法声明外部变量的最简单方法是什么?我唯一可以上班的是以下内容.必须有一个更简单的方法!

def hi;

def setMyVariable() {
    this.binding.setVariable("hi","hello world!")
}

setMyVariable()

println this.binding.getVariable("hi")
assert this.binding.getVariable("hi") == "hello world!"  //passes
assert hi == "hello world!"  //fails

解决方法

您可以为变量分配匿名函数,而不是定义方法:

def hi

def setMyVariable = {
    hi = "hello world!"
}

setMyVariable()
assert hi == 'hello world!'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读