我正在构建一个像 Flex 4.5 中的终端仿真器一样工作的管理 Controller 。 服务器端是使用Java编程语言的tomcat服务器上的Red5。
当用户在他的文本输入中输入命令时,该命令被发送到 red5,在 red5 中我检查命令是否存在并返回正确的输出,如果命令或参数不匹配则返回错误。
所以现在我使用 if (command.equals("..") {} else if (command.equals(...
有没有一种方法可以存储每个命令中应该执行的函数名称或对函数的引用并执行它?
例子:
// creating the hasmap
HashMap<String,Object> myfunc = new HashMap<String,Object>();
// adding function reference
myfunc.put("help",executeHelp);
或者……
myfunc.put("help", "executeHelp"); // writing the name of the function
然后
void receiveCommand(String command, Object params[]( {
myfunc.get(command).<somehow execute the referrened function or string name ? >
}
有什么想法吗?
谢谢!
最佳答案
您可以使用反射,但我建议使用更简单的方法。
您可以创建抽象类或接口(interface),并使用抽象方法执行。示例:
interface Command {
void execute(Object params[]);
}
class Help implements Command {
void execute(Object params[]) {
// do the stuff
}
}
现在你的 hashmap 可以是:
// creating the hasmap
HashMap<String,Command> myfunc = new HashMap<String,Command>();
// adding function reference
myfunc.put("help", new Help());
然后:
void receiveCommand(String command, Object params[]) {
myfunc.get(command).execute(params);
}
关于java - 我可以将函数名称存储在最终的 HashMap 中以供执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8200243/