gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:35:37 25 4
gpt4 key购买 nike

问题

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

最佳答案

在 Groovy 1.8.x 中,您可以这样做:

@groovy.transform.Field def hi

Variable annotation used for changing the scope of a variable within a script from being within the run method of the script to being at the class level for the script.

关于Groovy:如何从 groovy 脚本中的方法设置属性/字段/定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8557180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com