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

前端 未结 2 1879
鱼传尺愫
鱼传尺愫 2020-11-28 16:41

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 p

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 17:17

    I suggest that you use a Map instead:

    Create the map by doing

    Map values = new HashMap();
    

    Then change

    int temp = 10;
    

    to

    values.put("temp", 10);
    

    and access the value using

    int tempVal = values.get(temp_name);
    

提交回复
热议问题