Accessing a variable's value by name as a string in Java

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

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

Is it possible to access the value 10 with temp_name ?

+6
source share
2 answers

I suggest using Map<String, Integer> instead:

Create a map by completing

 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); 
+11
source

Make the variable a member variable and use reflection.

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

+10
source

Source: https://habr.com/ru/post/918673/


All Articles