In PHP, there is such a thing as:

$a = "name"; $$a = "Hello"; echo $name; // выводит "Hello" 

Tell me, how can this be implemented dynamically in Java? In general, it is interesting how to do this in Java, as in PHP in the example below:

 $name = "track"; for (i = 1; i <= 10; i++) { $temp = $name . $i; // Получаем track1 SendToFunction($$temp); //Передаем в функцию переменную $track1 } 

Why do I need it at all? I want instead of explicitly specifying track1 in track1.getDrawable()).getBitmap(); use the variable I need, so as not to write a lot of code, because Not all trackX I have to pass to the function

  • 7
    Horrible. In java, such perversions are not involved. - Sergey
  • In java there are no references to variables. Everything refers to specific instances of objects. Often such a php-shny reception is simply not needed. Two, three, 100,500 variables can simultaneously refer to the same object in a completely normal way. In other cases, there is always a solution. In fact, it is not clear what exactly you need, but you can store the tracks in the array, in the collection (the cycle seems to hint) or use the Map (as someone writes in your answer) - Sergey
  • Thank you for your comment. This is necessary in order not to use the switch case, but to loop through all the imageView and if there are “empty” ones just skip them - GosuUndeadGhost
  • maybe reflection will help you. But this is quite an extreme method. - pavel

1 answer 1

You can write in the Map correspondence of the name of the type Track1 variables, and get the necessary variables by name.
Specifically, using a variable by name is dynamically impossible, since Java not compiled dynamically, like PHP

 Map<String, Track> tracks = new HashMap<>(); tracks.put("Track1", new Track(<какие-то данные о треке>)); tracks.put("Track2", new Track(<какие-то данные о треке>)); tracks.put("Track3", new Track(<какие-то данные о треке>)); int i = 2; //надо передать Track2 в метод Track track = tracks.get("Track" + i); someMethod(track); 

I wrote on my knee, I could have mistaken the syntax, but the principle is this.

  • Thanks for your reply. Could you tell me how to implement it specifically in my example above? - GosuUndeadGhost
  • @pavel, what? What kind of reflection? And then she did? - Vladyslav Matviienko
  • @pavel, ok, and you are sure that your comment relates to my answer, and not to the author's question? - Vladyslav Matviienko
  • @GosuUndeadGhost, JS also compiles dynamically. Once again, in JAVA it will not work. - Vladyslav Matviienko