Java equivalent of function mapping in Python

前端 未结 7 1447

In python, if I have a few functions that I would like to call based on an input, i can do this:

lookup = {\'function1\':function1, \'function2\':function2, \'fu         


        
7条回答
  •  旧巷少年郎
    2021-02-04 15:43

    There are several ways to approach this problem. Most of these were posted already:

    • Commands - Keep a bunch of objects that have an execute() or invoke() method in a map; lookup the command by name, then invoke the method.
    • Polymorphism - More generally than commands, you can invoke methods on any related set of objects.
    • Finally there is Reflection - You can use reflection to get references to java.lang.Method objects. For a set of known classes/methods, this works fairly well and there isn't too much overhead once you load the Method objects. You could use this to, for example, allow a user to type java code into a command line, which you execute in real time.

    Personally I would use the Command approach. Commands combine well with Template Methods, allowing you to enforce certain patterns on all your command objects. Example:

    public abstract class Command {
      public final Object execute(Map args) {
        // do permission checking here or transaction management
        Object retval = doExecute(args);
        // do logging, cleanup, caching, etc here
        return retval;
      }
      // subclasses override this to do the real work
      protected abstract Object doExecute(Map args);
    }
    

    I would resort to reflection only when you need to use this kind of mapping for classes whose design you don't control, and for which it's not practical to make commands. For example, you couldn't expose the Java API in a command-shell by making commands for each method.

提交回复
热议问题