jcattau
jcattau

Reputation: 53

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"

String string2 = "B"

String string3 = "A"

String string4 = "B"

String 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:

[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.

I know I can do 5 if statements, but I know there has got to be a better way.

Upvotes: 0

Views: 907

Answers (1)

daggett
daggett

Reputation: 28564

you can set an object (class) member with obj[property] = value if it's a groovy object or map

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)

Upvotes: 1

Related Questions