问题
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?
回答1:
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 implement Callable with an anonymous class instance for each method call. Quite a bit more boilerplate code, but "type safe".
回答2:
You can achieve the same functionality as reflection by using the Command design pattern. It wraps action into objects, so they can be looked up and invoked using a common interface.
Read more here: http://en.wikipedia.org/wiki/Command_pattern
来源:https://stackoverflow.com/questions/13398885/call-different-methods-by-its-parameter