Use a variable within a variable?

2020-02-14 08:05发布

I have several fields, each one is like this:

field1
field2
field3
...

Using a loop with a counter, I want to be able to say fieldx. Where x is the value of the counter in that loop. This means if I have 6 entries in my array, fields1 - field6 will be given values.

Is fieldx possible?

3条回答
女痞
2楼-- · 2020-02-14 08:54

I think you would have to go through reflection. Have a look at the java.lang.reflect package, specifically the Field class.

查看更多
在下西门庆
3楼-- · 2020-02-14 08:55

You can do it with reflection, but in general it is better if you can declare your fields in an array. Instead of:

SomeType field1;
SomeType field2;
SomeType field3;
...
SomeType field6;

You can do this:

SomeType[] fields = new SomeType[6];

Then you can loop over the array setting the values:

for (int i = 0; i < fields.length; ++i)
{
    fields[i] = yourValues[i];
}
查看更多
Emotional °昔
4楼-- · 2020-02-14 09:05

As an alternative using a plain ol' array (see Mark's answer), you could use an Arraylist. Declare your fields like so:

ArrayList<SomeType> fields = new ArrayList<SomeType>();

Then after putting in the fields (most likely using fields.add(SomeType t), you can iterate using:

for (Sometype t : fields)
{
    // Do stuff with t
}

ArrayLists have all the same features of arrays with some additional benefits, like compatibility with generics.

Also note that as of Java 5, you can use for-each loops with arrays! So, instead of keeping track of indeces and remembering whether you need to call length or size(), you can use a for-each loop.

查看更多
登录 后发表回答