1

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.

2

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. I forgot about the switch case. It kind of sucks Java doesn't have something like that.
-1

we can use

java.lang.reflect.Method Something like

java.lang.reflect.Method method;
try {
    method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
catch (NoSuchMethodException e) { ... }

The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName).

And your possible solution can be like -

package com.test.pkg;
public class MethodClass {
  public int getFishCount() {
    return 5;
 }
 public int getRiceCount() {
    return 100;
 }
 public int getVegetableCount() {
    return 50;
 }
}
package com.test.pkg;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
    public static void main(String[] args) {
        MethodClass classObj = new MethodClass();
        Method method;
        String commandString = "Fish";
        try {
            String methodName = "get" + commandString + "Count";
            method = classObj.getClass().getMethod(methodName);
            System.out.println(method.invoke(classObj));          //equivalent to System.out.println(testObj.getFishCount());
        } catch (SecurityException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

Ref: How do I invoke a Java method when given the method name as a string?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.