问题
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.
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.
so for now i use if (command.equals("..") {} else if (command.equals(...
Is there a way to store the function name or a reference to the function that should be executed in each command and to execute it?
example:
// creating the hasmap
HashMap<String,Object> myfunc = new HashMap<String,Object>();
// adding function reference
myfunc.put("help",executeHelp);
or....
myfunc.put("help", "executeHelp"); // writing the name of the function
and then
void receiveCommand(String command, Object params[]( {
myfunc.get(command).<somehow execute the referrened function or string name ? >
}
any ideas?
thank you!
回答1:
You could use reflection, but I suggest a easier way.
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());
And then:
void receiveCommand(String command, Object params[]) {
myfunc.get(command).execute(params);
}
回答2:
You can execute a function by name as follows:
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
In the above snippet, param1.class, param2.class are the class types of the arguments of the method to execute.
Then:
try {
method.invoke(obj, arg1, arg2,...);
}
catch (IllegalArgumentException e) { }
catch (IllegalAccessException e) { }
catch (InvocationTargetException e) { }
There is lots more information about this here: http://java.sun.com/docs/books/tutorial/reflect/index.html
回答3:
You can define an interface for your functions
interface Function {
public Object invoke(Object[] arguments);
}
and then public your code via this interface
public class Function1 implements Function {
public Object invoke(Object[] arguments) {
...
}
}
and store in the map
map.put("helpCommand", new Function1());
or store a reference using an anonymous class
Function theFunction = new Function() {
public Object invoke(Object[] arguments) {
return theRealMethod(arguments[0], String.valueOf(arguments[1]));
}
}
In the second example I showed how to use the anonymous class as an adaptor if the method you want to call has a different signature than your interface.
来源:https://stackoverflow.com/questions/8200243/can-i-store-function-names-in-final-hashmap-for-execution