Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i store function names in final hashmap for execution?

Tags:

java

dynamic

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!

like image 700
ufk Avatar asked Dec 02 '22 00:12

ufk


2 Answers

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);
}
like image 193
Raul Guiu Avatar answered Dec 20 '22 17:12

Raul Guiu


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

like image 30
Jonathan Schneider Avatar answered Dec 20 '22 17:12

Jonathan Schneider