开发者

Use Var from For Loop in Java

I'm sorry I'm really new to Java, I'm working on friends project. I seem to be struggling with this one. I'm trying to use a really simple for-loop to iterate through several variables that I get fro开发者_如何学编程m another class.

for (int i = 0; i < 8; i = i + 1) { // Test and Loop
    myarr.add(anotherclass.SVAR+i);
}

I'm not sure why they were not originally put into an Array (maybe because its easier to access them as strings?). In any case they are set like SVAR0, SVAR1 up to SVAR7. How can I do this? When I have my SVAR+i, it says SVAR is not defined, which makes sense because it's not.

Thank you ahead of time!


You can't dynamically construct a reference to a variable / field etc. like that. The compiler needs an explicit reference.

You may wish to use reflection, however, to derive the name, and then introspect on your object to find that field and retrieve the value. Here's a simple example to illustrate how you'd do this.

However I think a better object/field structure may be more appropriate (depending on your use case etc.)


Replace the variables with an array, or unroll the loop. What you want is possible, but only at great expense through VM introspection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜