有没有办法循环变量名? [英] Is there any way to loop though variable names?

查看:119
本文介绍了有没有办法循环变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,例如我有以下变量:
Var1,Var2,Var3,Var4,Var5 - 共有5个变量。
所有具有唯一的数据,我想通过for循环来循环。

  // String Var1 = something ,Var2 =等等。
for(int i = 1; i <= 5; i ++)
{
Var(i)=别的东西;
}
//i.e我将Var(1),Var(2)等等分别改为别的东西。

为了进一步阐明,最终我想应用这个方法遍历我的程序中的多个组件。我有大量带有样式名称的组件(例如label1,label2,label3等),并且想要更改这些组件的值,而不必单独设置它们的值。

解决方案

如果变量定义为类的成员,则可以使用反射来完成。对于方法参数或局部变量,这是不可能的。类似于这个:

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





$ b如果你打算改变它的值,必须考虑变量的类型。例如。你可以给一个 Object 类型的变量赋值一个 String ,但不能反过来。


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.

解决方案

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.

这篇关于有没有办法循环变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆