Java – is there a way to loop variable names?

For example, I have the following variables:

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

For further clarification, I finally want to apply this method to iterate over multiple components in my program I have a large number of components with style names (such as label1, label2, label3, etc.) and want to change the values of these components without setting their values separately

Solution

If you define a variable as a member of a class, you can do this using reflection It is not possible for method parameters or local variables Something similar:

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

If you plan to change the value, it becomes a little complicated because you must also consider the type of variable For example You can assign string to a variable of type object, but not vice versa

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>