Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to loop though variable names?

So for example I have the following variables: Var1, Var2, Var3, Var4, Var5 - a total of 5 variables. All with unique data and I want to loop though them using a for loop.

//String Var1 = something, Var2 = something etc..
for (int i = 1; i <= 5; i++)
{
Var(i) = "something else";
}
//i.e I change Var(1), Var(2) etc.. to something else respectively.

To clarify further, ultimately I want to apply this method to iterate through multiple components in my program. I have a large number of components with styled names(e.g. label1, label2, label3 etc..) and want to change the value of these components without having to individually set their value.

like image 854
Dane Brouwer Avatar asked Oct 17 '15 10:10

Dane Brouwer


2 Answers

You can do it with reflection, if the variables are defined as members of a class. For method parameters or local variables it is not possible. Something similar to this:

Class currentClass = getClass();
Field[] fields = currentClass.getFields();
for (Field f : fields) {
  System.out.println(f.getName());
}

If you intend to change the value it becomes a bit more complicated as you also have to consider the type of the variable. E.g. you can assign a String to a variable of type Object but not the other way around.

like image 166
hotzst Avatar answered Sep 20 '22 00:09

hotzst


I would suggest to go for an array if data type of variables are same. You can try something like that

        String[] Var = {"something","something2","something else"};
        for (String var : Var)
        {
        System.out.println(var);
        }
like image 31
Prince Avatar answered Sep 21 '22 00:09

Prince