2011-11-20 52 views
4

我正在构建一个管理控制器,它像Flex 4.5中的终端仿真器一样工作。 服务器端是使用Java编程语言的tomcat服务器上的Red5。我可以存储函数名称在最终的hashmap中执行吗?

当用户在他的文本输入中输入命令时,该命令被发送到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 ? > 
} 

什么想法?

谢谢!

回答

7

你可以使用反射,但我建议一个更简单的方法。

您可以使用抽象方法execute创建抽象类或接口。例如:

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

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

现在你的HashMap可以是:

​​

然后:

void receiveCommand(String command, Object params[]) { 
    myfunc.get(command).execute(params); 
} 
+2

是的,这是更安全,更有条理。 – cherouvim

+0

谢谢你!并感谢@cherouvim的评论! – ufk

5

可以按名称如下执行功能:

java.lang.reflect.Method method; 
try { 
    method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); 
} catch (SecurityException e) { 
    // ... 
} catch (NoSuchMethodException e) { 
    // ... 
} 

在上面的代码中,param1.class, param2.class是执行该方法的自变量的类类型。

然后:

try { 
    method.invoke(obj, arg1, arg2,...); 
} 
catch (IllegalArgumentException e) { } 
catch (IllegalAccessException e) { } 
catch (InvocationTargetException e) { } 

还有其它更多的信息,关于这个位置:http://java.sun.com/docs/books/tutorial/reflect/index.html

3

您可以通过这个接口定义一个接口为您的功能

interface Function { 
    public Object invoke(Object[] arguments); 
} 

,然后公开你的代码

public class Function1 implements Function { 
    public Object invoke(Object[] arguments) { 
     ... 
    } 

}

,并存储在地图

map.put("helpCommand", new Function1()); 

或使用匿名类

Function theFunction = new Function() { 

    public Object invoke(Object[] arguments) { 
     return theRealMethod(arguments[0], String.valueOf(arguments[1])); 
    } 
} 

在第二个例子我展示如何使用匿名类为适配器存储参考如果您想调用的方法与您的界面有不同的签名。

相关问题