Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a method from a given string in Java

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading