[英]Assign class variables with a loop in groovy
I'm having some trouble figuring out how to accomplish what I am looking for.我在弄清楚如何完成我正在寻找的东西时遇到了一些麻烦。 Let's say I have 5 different String variables: String string1 = "A"
假设我有 5 个不同的字符串变量: String string1 = "A"
String string2 = "B"字符串 string2 = "B"
String string3 = "A"字符串 string3 = "A"
String string4 = "B"字符串 string4 = "B"
String string5 = "A"字符串 string5 = "A"
What I want to do is loop over those 5 variables and if they equal B, I want to set them to A. What I have tried is something like:我想要做的是遍历这 5 个变量,如果它们等于 B,我想将它们设置为 A。我尝试过的是:
[string1,string2,string3,string4,string5].each {
if (it == "B"){
//don't know what to put here
need to set variable = "A" here
}
}
I don't know how to get the actual variable name in the closure for the assignment.我不知道如何在分配的闭包中获取实际的变量名称。 Maybe I am not searching correctly for what I am trying to do, but I need to be able to set strin2 and string4 to "A" with this loop.
也许我没有正确搜索我正在尝试做的事情,但我需要能够使用这个循环将 strin2 和 string4 设置为“A”。
I know I can do 5 if statements, but I know there has got to be a better way.我知道我可以做 5 个 if 语句,但我知道必须有更好的方法。
you can set an object (class) member with obj[property] = value
if it's a groovy object or map如果是 groovy object 或 Z1AEZB5DC8ED51244051E,您可以使用
obj[property] = value
设置 object (类)成员
for example例如
@groovy.transform.ToString
class X {
String string1 = "A"
String string2 = "B"
String string3 = "A"
String string4 = "B"
String string5 = "A"
void switchAll(vOld,vNew){
this.getProperties().each{k,v->
if(k ==~ /string\d+/ && v==vOld) this[k] = vNew
}
}
}
def x = new X()
println x
x.switchAll("B","C")
println x
prints:印刷:
X(A, B, A, B, A)
X(A, C, A, C, A)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.