Is it possible to store the name of an int
variable in a string and use that string as a parameter to update the int
?
Yes, this is called reflection.
You are interested in the Field class.
Example:
static class A {
public int x = 0;
}
public static void main(String[] args) throws Exception {
A a = new A();
Field f = A.class.getField("x");
f.set(a, 5);
System.out.println(a.x);
}
Note that though it is possible - it is not advised to use reflection except for rare cases, it has some major draw backs (maintainability, safety, performance...) - which makes the alternatives usually better choices.
Using reflection in this case would be overkill. You can obtain the intended behavior by simply using a Map
:
Map<String, Integer> variables = new HashMap<String, Integer>();
Then the keys to the map will be the variable names, and the values the actual values:
variables.put("var1", 10);
variables.put("var2", 20);
Later on, you'll retrieve the values like this:
Integer n1 = variables.get("var1"); // n1 == 10
Integer n2 = variables.get("var2"); // n2 == 20
And if you need to update the values:
variables.put("var1", variables.get("var1") + 32);
Integer n3 = variables.get("var1"); // n3 == 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With