作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定一个简单的 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/
我是一名优秀的程序员,十分优秀!