'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:
"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 1:[1]
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.
Solution 2:[2]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Captain Giraffe |
| Solution 2 | Rakib Hasan |
