我正在构建一个管理控制器,它在Flex 4.5中像终端模拟器一样工作.服务器端是使用Java编程语言的tomcat服务器上的Red5.
当用户在他的textinput中输入命令时,该命令被发送到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);
Run Code Online (Sandbox Code Playgroud)
要么....
myfunc.put("help", "executeHelp"); // writing the name of the function
Run Code Online (Sandbox Code Playgroud)
然后
void receiveCommand(String command, Object params[]( {
myfunc.get(command).<somehow execute the referrened function or string name ? >
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
谢谢!
你可以使用反射,但我建议一种更简单的方法.
您可以使用抽象方法execute创建抽象类或接口.例:
interface Command {
void execute(Object params[]);
}
class Help implements Command {
void execute(Object params[]) {
// do the stuff
}
}
Run Code Online (Sandbox Code Playgroud)
现在你的hashmap可以是:
// creating the hasmap
HashMap<String,Command> myfunc = new HashMap<String,Command>();
// adding function reference
myfunc.put("help", new Help());
Run Code Online (Sandbox Code Playgroud)
然后:
void receiveCommand(String command, Object params[]) {
myfunc.get(command).execute(params);
}
Run Code Online (Sandbox Code Playgroud)
您可以按名称执行函数,如下所示:
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中,param1.class, param2.class是要执行的方法的参数的类类型.
然后:
try {
method.invoke(obj, arg1, arg2,...);
}
catch (IllegalArgumentException e) { }
catch (IllegalAccessException e) { }
catch (InvocationTargetException e) { }
Run Code Online (Sandbox Code Playgroud)
这里有更多相关信息:http://java.sun.com/docs/books/tutorial/reflect/index.html
| 归档时间: |
|
| 查看次数: |
4139 次 |
| 最近记录: |