0

I need to allow the user to target a variable using a string name. Example,

int number = 5;

String variableTarget = "number";

I need to target the int, number, and then change its value in later code. Any way?

I cannot think of any way to do it. There seems to be alot of class targeting, but I already have that.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

1

I don't think that there is a way to do this in java. But, to have such a functionality, you can use a map to assign the value to the number key in the Map :

HashMap <String, Integer> myMap = new HashMap<>();
myMap.put("number", 5);

and you can alter the value later using the same put statment :

myMap.put("number", myMap.get("number")+1);
0

You can use Java Reflections, or create another structure like a HashMap answered by @DodgyCodeException

Fragalli
  • 229
  • 2
  • 7