简体   繁体   English

在Java中以字符串的形式访问变量的值

[英]Accessing the value of a variable by its name as string in 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 ? 是否可以使用temp_name访问值10

I suggest that you use a Map<String, Integer> instead: 我建议您使用Map<String, Integer>代替:

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);

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. 然后,您可以使用java.lang.reflect包来检索该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM