I'm looking for a way to call any given method in my class without having to do the whole try-catch
statement.
EXAMPLE:
public void Worker(String handle) throws Exception
{
if(PROTOCOL.contains(handle))
{
System.out.println("good");
Worker.handle;
}
else {
throw new Exception("Don't understand <" + handle + ">");
}
}
PROTOCOL
is a list of allowed commands.
I know I can say if(input = ....){do....}
but I want to be able to do the above; call my class with the input value.
Is this possible?
Depending on what your commands would look like you could use a Map<String, Command>
which you'd then use like this:
Map<String, Command> PROTOCOL = ... //you build that map somehow
Command c = PROTOCOL.get(handle);
if( c != null ) {
System.out.println("good");
c.execute();
} else {
throw new Exception("Don't understand <" + handle + ">");
}
Command
could then be a class or function interface:
interface Command {
void execute();
}
Used as a class interface
class MyCommand implements Command {
//this can have private data
void execute() {
//do whatever is needed
}
}
PROTOCOL.put("mycommand", new MyCommand(/*you could pass parameters here*/));
Advantages:
String getName()
as well.AddCommand(1)
and AddCommand(-1)
).PROTOCOL
. That way you could even add commands via some plugin mechanism.Used as a function interface (e.g. via lambdas)
PROTOCOL.put("mycommand", () -> {
//do whatever is needed
});
Advantages: