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

给定一个简单的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!'

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...