0

I want to call a method in java with a given string like this for example:

String string = "HelloWorld";
main.string();

I want something like this to call the method defined in the string, would that be possible? If not (which I am kind of expecting), are there alternatives?

Kileraptor1
  • 11
  • 1
  • 7

1 Answers1

0

There are two main possibilities:

  • you know wich methods can be called from a particular string
  • you don't know wich methods can be called

If you know wich methods can be called you only need to do something like

switch(str) {
    case "first":
        obj.firstMethod();
        break;
    case "second":
        obj.secondMethod();
        break;
}

if you don't know wich methods can be called and the string represent the name of the method you can use the reflection as other already commented

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56