I am trying to reduce my code from using a bunch of if statements from getting a specified command and calling a method for it.
Instead, I want to try something that would take that command and call a method name with it
Something like this:
"get" + commandString + "Count"()
Instead of:
if (command == "something") {
callSomeMethod();
}
if (command == "somethingelse") {
callSomeOtherMethod();
}
...
Is there a way to call a method from a specified string? Or a better way to approach this problem.
>Solution :
This is the use-case for a switch case statement.
switch(command){
case "command1": command1(); break;
case "command2": command2(); break;
Using a string javascript style is fortunately impossible in Java. The comments links to answers how to use reflection to accomplish something similar. This is rarely a good solution.