Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a variable by name, which isn't known while compiling

Tags:

java

variables

Is it possible to set a variable, if i want to have it flexible? I think an exmaple makes it easier to understand.

String hallo1;
String hallo2;

for(int i = 0; i < 2; i++) {
 hallo & i = Integer.toString(i);
}
like image 341
rakete Avatar asked Dec 02 '22 06:12

rakete


2 Answers

No, you cannot. There's (fortunately) no such thing as eval() in Java.

Your best bet is to grab an Array or an ArrayList. Here's an Array example:

String[] hallos = new String[2];

for (int i = 0; i < 2; i++) {
    hallos[i] = Integer.toString(i);
}
like image 83
BalusC Avatar answered Dec 05 '22 08:12

BalusC


It's technically possible with reflection, but I would advise against it unless you have a really good reason to do it. It would make your code much more difficult to debug and to read.

EDIT:
As the comments stressed:

  1. To clarify, I strongly suggest not to be tempted to use reflection. The other answers point out better ways to achieve your goal, such as an array.
  2. Reflection won't help you with local variables.
like image 43
Eli Acherkan Avatar answered Dec 05 '22 09:12

Eli Acherkan