mercredi 27 janvier 2021

Java: How to select/call a function by a strings content?

I have a list and I have functions.

I want to iterate the list and call the function that matches the lists element. How can I do that in a more elegant way than comparing the name in a if or switch?

class C
{
  String [] lst = {"foo", "bar", "zoo"};

  void foo () { /* ... */ }
  void bar () { /* ... */ }

  void NotSoElegant ()
  {
    for (String s : lst)
    {
      if (s.equals ("foo") == true)
      { foo (); }
      if (s.equals ("bar") == true)
      { bar (); }
    }
  }
}




Aucun commentaire:

Enregistrer un commentaire