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?