通过其参数调用不同的方法 [英] Call different methods by its parameter
问题描述
我有一个应用程序,该应用程序应根据参数的输入调用不同的方法.到目前为止,我的想法基本上是,我创建一个Switch并根据其大小分别调用方法.示例:
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:
但是我从其中一个答案中得知,这是不安全的.你们怎么看?
But then I read from one of the answers, that it's not safe. What do you guys think?
推荐答案
如果您需要从字符串转到方法调用,则反射可能是您的最佳选择.不会涉及重大安全问题,尤其是如果您限制允许调用的方法集时.使用Map<String, Method>
是实现它的一种方法,它具有改进的性能,因为主要瓶颈不是反射方法调用,而是方法查找.
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.
无需反思,您可以使用Map<String, Callable>
实现此目标,其中您为每个方法调用使用匿名类实例实现Callable
.样板代码要多一些,但是类型安全".
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".
这篇关于通过其参数调用不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!