我可以在最终的哈希图中存储函数名称以便执行吗? [英] can i store function names in final hashmap for execution?

查看:70
本文介绍了我可以在最终的哈希图中存储函数名称以便执行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个管理控制器,其功能类似于Flex 4.5中的终端模拟器。
服务器端是使用Java编程语言的tomcat服务器上的Red5。

I'm building an admin controller that work like a terminal emulator in Flex 4.5. The server side is Red5 on a tomcat server using Java programming language.

当用户在文本输入中输入命令时,该命令将发送到red5 ,在red5中,我检查命令是否存在,如果命令或参数不匹配,则返回正确的输出或错误。

When a user enter a command in his textinput, the command is sent to the red5, in red5 I check if the command exists and return a proper output or an error if the command or parameters don't match.

所以现在我使用 if(command.equals( ..){}否则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 ? >
}

有什么想法吗?

谢谢!

推荐答案

您可以使用反射,但是我建议一种更简单的方法。

You could use reflection, but I suggest a easier way.

您可以创建带有抽象方法execute的抽象类或接口。示例:

You can create an abstract class or interface with an abstract method execute. Example:

interface Command {
    void execute(Object params[]);
}

class Help implements Command {
    void execute(Object params[]) {
        // do the stuff
    }
}

现在您的哈希图可以是:

Now your hashmap can be:

// 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);
}

这篇关于我可以在最终的哈希图中存储函数名称以便执行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆