-4

How can I access the variable value by providing the String that contains name of that variable? Like this:

int var1 = 123;
getVariableByName("var1");

It should return 123
I know that I can create a HashMap or something...
But can I do this shortly, without a couple of code?

I need to create some objects with similar data, so I did this:
(I'm working with android)

String string2="bla";
String string2="bla-bla";
String string3="bla-bla-bla"

for(int i=1; i<=2; i++){
   TextView tv = new TextView;
   TextView.setText(getValueOf("string"+i));
}

Just it isn't smart to make a huge HashMap if you need to create a lot of objects. There should be a way to do it optimised...

Vitalis11
  • 25
  • 5

1 Answers1

0

You can't do that with local variables in Java. Local variables are variables you define inside a method. The names do not survive compilation step and are not available at runtime.

You can lookup fields via reflection via Foo.class.getField or obj.getClass().getField

Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
Lev Kuznetsov
  • 3,235
  • 4
  • 18
  • 33