在Java中以字符串的形式访问变量的值 [英] Accessing the value of a variable by its name as string in Java
本文介绍了在Java中以字符串的形式访问变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含变量名的字符串。我想获得该变量的值。
int temp = 10;
String temp_name =temp;
是否可以访问值 10
使用 temp_name
?
解决方案
我建议您使用 Map< String,Integer>
代替:
通过执行来创建地图
Map< String,Integer> values = new HashMap< String,Integer>();
然后更改
int temp = 10;
到
values.put(temp,10);
并使用
<$ p $访问该值p>
int tempVal = values.get(temp_name);
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
?
解决方案
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);
这篇关于在Java中以字符串的形式访问变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文