Storing int variable name in String

Is it possible to save the name of the int variable in a string and use this string as a parameter for updating int ?

+4
source share
3 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(ax); } 

Please note that although it is possible - it is not recommended to use reflection, except in rare cases, it has some basic back spins (maintainability, safety, performance ...), which makes the alternatives usually the best.

+4
source

Using reflection in this case would be redundant. You can get the expected behavior simply using Map :

 Map<String, Integer> variables = new HashMap<String, Integer>(); 

Then the keys to the map will be the names of the variables, and the values ​​are real values:

 variables.put("var1", 10); variables.put("var2", 20); 

You will later get values ​​similar to 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 
+3
source

The context of your question is incomprehensible - Map<String, Integer> can do what you need:

 Map<String, Integer> map = new HashMap<String, Integer> (); map.put("int1", 1); map.put("int2", 2); //now retrieve the ints based on their name int int1 = map.get("int1"); 
+2
source

Source: https://habr.com/ru/post/1441161/


All Articles