Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing the name of an int variable in a String

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?

like image 621
Marvin D Avatar asked Jan 15 '23 06:01

Marvin D


2 Answers

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.

like image 53
amit Avatar answered Jan 17 '23 19:01

amit


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
like image 34
Óscar López Avatar answered Jan 17 '23 20:01

Óscar López