Search code examples
javauser-inputshortcut

Calling a method from user input in JAVA


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?


Solution

  • 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:

    • The interface can have more than 1 method, e.g. it could have a String getName() as well.
    • Commands can have parameters, e.g. you could provide one implementation and use different names that are bound to the same command with different parameters (e.g. a "increment" and "decrement" could be bound to AddCommand(1) and AddCommand(-1)).
    • You could use some dependency inversion mechanism (e.g. via CDI) to have commands register themselves to PROTOCOL. That way you could even add commands via some plugin mechanism.
    • Using interfaces for classes might be easier to grasp for others.
    • Easier to structure for larger commands as you can easily extract the classes into separate files.

    Used as a function interface (e.g. via lambdas)

    PROTOCOL.put("mycommand", () -> { 
      //do whatever is needed
    });
    

    Advantages:

    • No classes needed which can be more concise for short commands.