Java中等效于Python中的函数映射 [英] Java equivalent of function mapping in Python

查看:134
本文介绍了Java中等效于Python中的函数映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,如果我有几个函数需要根据输入调用,我可以这样做:

  lookup = {'function1':function1,'function2':function2,'function3':function3} 
lookup [input]()

这就是我有一个映射到该函数的函数名字典,并通过字典查找来调用该函数。



在java中如何做到这一点?

解决方案

有几种方法可以解决这个问题。大多数已经发布:


  • Polymorphism - 比命令更普遍,您可以在任何相关的对象集上调用方法。
  • 最后有反射 - 您可以使用反射获取对java.lang.Method对象的引用。对于一组已知的类/方法,这种方法工作得很好,加载Method对象后开销不会太大。例如,您可以使用它来允许用户将Java代码键入到您实时执行的命令行中。


我个人会使用Command命令。命令与模板方法很好地结合在一起,允许您在所有命令对象上执行某些模式。例子:

pre $ public abstract class Command {
public final Object execute(Map< String,Object> args){
//在此执行权限检查或事务管理
Object retval = doExecute(args);
//在这里记录,清理,缓存等
return retval;
}
//子类覆盖这个来做真正的工作
protected abstract Object doExecute(Map< String,Object> args);
}

只有当您需要使用这种映射那些你不能控制的设计类,并且不适合做命令。例如,您不能通过为每个方法发出命令而在命令行中公开Java API。


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, 'function3':function3}
lookup[input]()

That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.

How to do this in java?

解决方案

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<String, Object> 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<String, Object> 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.

这篇关于Java中等效于Python中的函数映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆