Ros*_*oss 9 python java function
在python中,如果我有一些我想根据输入调用的函数,我可以这样做:
lookup = {'function1':function1, 'function2':function2, 'function3':function3}
lookup[input]()
Run Code Online (Sandbox Code Playgroud)
那就是我有一个映射到该函数的函数名字典,并通过字典查找来调用该函数.
如何在java中执行此操作?
Dan*_*ton 15
Java没有一流的方法,所以命令模式是你的朋友......
disclamer:代码未经测试!
public interface Command
{
void invoke();
}
Map<String, Command> commands = new HashMap<String, Command>();
commands.put("function1", new Command()
{
public void invoke() { System.out.println("hello world"); }
});
commands.get("function1").invoke();
Run Code Online (Sandbox Code Playgroud)
有几种方法可以解决这个问题。其中大部分已经发布:
我个人会使用命令方法。命令与模板方法很好地结合在一起,允许您在所有命令对象上强制执行某些模式。例子:
public abstract class Command {
public final Object execute(Map<String, Object> args) {
// do permission checking here or transaction management
Object retval = doExecute(args);
// do logging, cleanup, caching, etc here
return retval;
}
// subclasses override this to do the real work
protected abstract Object doExecute(Map<String, Object> args);
}
Run Code Online (Sandbox Code Playgroud)
仅当您需要对您无法控制其设计且无法发出命令的类使用这种映射时,我才会诉诸反射。例如,您无法通过为每个方法创建命令来在命令 shell 中公开 Java API。