Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the value of a variable by its name as string in Java

Tags:

java

I have a string containing the variable name. I want to get the value of that variable.

int temp = 10;
String temp_name = "temp";

Is it possible to access the value 10 by using temp_name?

like image 586
bazzinga Avatar asked Jun 21 '12 15:06

bazzinga


2 Answers

I suggest that you use a Map<String, Integer> instead:

Create the map by doing

Map<String, Integer> values = new HashMap<String, Integer>();

Then change

int temp = 10;

to

values.put("temp", 10);

and access the value using

int tempVal = values.get(temp_name);
like image 130
aioobe Avatar answered Sep 28 '22 12:09

aioobe


Make the variable a member variable and use reflection.

You cannot get the value by name of a variable unless it's a member variable of a class. Then you can use the java.lang.reflect package to retrieve the value.

like image 37
Erick Robertson Avatar answered Sep 28 '22 12:09

Erick Robertson