Reputation: 305
I'm doing a bit of a side project at the moment, and was wondering if it's possible to retrieve values from variables refering only to a String which shares the same name.
i.e.
int x,y,z;
String sa [] = {"x","y","z"};
//then loop through sa, and get the values associated with each name and store them into a different
//container.
Upvotes: 2
Views: 83
Reputation: 9907
Sort of like:
int x = 4;
y = GetVariable("x");
System.out.println(y);
Output: 4
No, it's not unfortunately. Java doesn't store it's variable names.
Maybe you could give us an example of what you are trying to do to see if there is a better solution.
Upvotes: 0
Reputation: 1499870
If they're instance or static variables, you can do this using reflection to get the fields - but it would usually be better to use a Map<String, Integer>
.
If you can tell us more about what you're trying to achieve in your side project that would help, but generally if you want to dynamically associate keys with values, you should use a map. For example:
Map<String, Integer> map = new Map<String, Integer>();
map.put("x", 10);
map.put("y", 20);
map.put("z", 30);
Integer z = map.get("z"); // z is now 30...
Upvotes: 3
Reputation: 340693
Are you asking whether it's possible to read a
local variable having "a"
string? No.
However if a
, b
and c
are fields, you can use reflection to obtain their values.
Upvotes: 1
Reputation: 19787
Yes, it is possible, through the Reflection API: http://docs.oracle.com/javase/tutorial/reflect/
Upvotes: 2