6

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?

1
  • Why? For what reason? What purpose are you trying to accomplish? Commented Jun 22, 2012 at 0:23

2 Answers 2

11

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);
Sign up to request clarification or add additional context in comments.

2 Comments

+1 This is a better solution to the problem, and there should be no reason why you cannot take this approach.
@ErickRobertson I agree. Reflection is a solution to a 'not ordinary' need, whereas a newbie is typically needing a map or associative array.
10

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.