I am following this question
How to generically implement calling methods stored in a HashMap?
I am trying to pass parameters while calling executeCommand
function
Example code is as follows,
InvokesMethodItf
public interface InvokesMethodItf {
public void invokeMethod(String data) throws Exception; //pass the data as parameter
public void setMethod(Method method);
}
InvokesMethod
public class InvokesMethod implements InvokesMethodItf{
private Method method;
@Override
public void invokeMethod(String data) throws Exception {
method.invoke(data); //pass the data to invoke (I think my problem is here). I dont know how to pass it.
}
@Override
public void setMethod(Method method) {
this.method = method;
}
}
Terminal
public class Terminal {
public HashMap<Character, InvokesMethodItf> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethodItf>();
}
private void setCommand(char letter, Method method) {
InvokesMethodItf inv = new InvokesMethod();
inv.setMethod(method);
this.commands.put(letter, inv);
}
public void executeCommand(char letter, String data) throws Exception {
this.commands.get(letter).invokeMethod(data); //pass data to invoke method
}
}
Main
public class Main {
Terminal commandLine = new Terminal();
commandLine.setCommand('h',test()); //This should give syntax error or i am not sure
commandLine.executeCommand('h', "This is a test");
public Method test(String data){
Log.d("Test", data);
return null;
}
}
UPDATE: I am trying to set multiple methods using setCommand and execute it.
commandline.setCommand('p',this.getClass().getDeclaredMethod("parseData",String.class,Integer.class), this);
commandline.setCommand('p', this.getClass().getDeclaredMethod("test"), this);
Then , calling
commandline.executeCommand('p', "test", 2345);
Only test function is calling.(Last setCommand function is running). I think it is overwriting Method
. Isn't there is someway to pass multiple methods in setCommand function. Changing type of Method
to Method[]
is not working either.