I got an application which should call different methods, based on the params’ input. My idea until now is basically, that I create a Switch and call the methods separately by its case. Example:
switch (methodName)
{
case "method1":
method1();
break;
case "method2":
method2();
break;
default:
System.out.println(methodName + " is not a valid method!");
}
I was considering the option to invoke the method by its given string, as provided in this question:
How do I invoke a Java method when given the method name as a string?
But then I read from one of the answers, that it’s not safe. What do you guys think?
If you need to go from a string to a method call, reflection may be your best option. There are no great safety issues involved, especially if you constrain the set of methods that are allowed to be called. Using a
Map<String, Method>is one way to achieve it, with the benefit of improved performance since the main bottleneck is not reflective method invocation, but method lookup.Without reflection you could achieve this with a
Map<String, Callable>, where you implementCallablewith an anonymous class instance for each method call. Quite a bit more boilerplate code, but “type safe”.