在java中调用基于字符串名称的函数(Invoking a functions based on string name in java)
我需要一个逻辑来替换下面的代码。
void invokeMethod(String action){ if ("echo".equals(action)) { //call echo echo(); } else if ("dump".equals(action)) { // call dump dump(); } ... goes on }切换大小写字符串参数在java 1.6中不起作用。 我可以做得更好吗?
I need a logic to replace the following code.
void invokeMethod(String action){ if ("echo".equals(action)) { //call echo echo(); } else if ("dump".equals(action)) { // call dump dump(); } ... goes on }switch case with string parameter won't work in java 1.6. Can I do it a better way ?
最满意答案
我使用了一个带有动作的java hashmap作为键值和随机整数值。 无论何时需要调用perticular动作,从hashmap获取整数并使用switch case(在上面的问题中,字符串比较非常操作,用整数代替)。
I used a java hashmap with action as key and random integer as value. Whenever perticular action is asked to invoke, fetch the integer from the hashmap and use switch case now (In above problem, string comparison was very operation, replaced the same with integers).
更多推荐
发布评论