简体   繁体   English

从HashMap存储和调用方法

[英]Store and call method from a HashMap

I have 2 files: ImplementationProvider and CaseHandler. 我有2个文件:ImplementationProvider和CaseHandler。

ImplementationProvider: ImplementationProvider:

class ImplementationProvider {
    public void method1(Object[] params) {}
    public void method2(Object[] params) {}
    ...
    public void method100(Object[] params) {}
}

CaseHandler: CaseHandler:

class CaseHandler {
    ImplementationProvider ip; // auto injected
    public void handle(String s, String param) {
        switch(s) {
            case USE_CASE_ONE: ip.method1(param); break;
            case USE_CASE_TWO: ip.method2(param); break;
            ...
        }
    }   
}

How can I refactor the CaseHandler so that the USE_CASE strings are keys in a HashMap where the values would be the methods? 我如何重构CaseHandler,以便USE_CASE字符串是HashMap中的键,其中值是方法? The main issue I'm having is the propagation of the parameters. 我遇到的主要问题是参数的传播。 Other answers here recommend using an interface, however I need to provide the parameter on runtime. 此处的其他答案建议使用接口,但是我需要在运行时提供参数。

Here's one way I can think of, using the Consumer functional interface: 这是使用Consumer功能介面的一种方法:

Map<String,Consumer<Object[]>> methods = new HashMap<>();

methods.put (USE_CASE_ONE, param -> ip.method1(param));
methods.put (USE_CASE_TWO, param -> ip.method2(param));
...

public void handle(String s, String param) {
    methods.get(s).accept(new Object[]{param});
}

EDIT: 编辑:

If your methods require two parameters, you can use the BiConsumer interface: 如果您的方法需要两个参数,则可以使用BiConsumer接口:

Map<String,BiConsumer<String,List<String>>> methods = new HashMap<>();

methods.put (USE_CASE_ONE, (s,l) -> ip.method1(s,l));
methods.put (USE_CASE_TWO, (s,l) -> ip.method2(s,l));
...

public void handle(String s, String param) {
    methods.get(s).accept(someString,someListOfStrings);
}

If you are using Java 8, you can lever the Consumer functional interface to parametrize your map's values with. 如果您使用的是Java 8,则可以利用“ Consumer功能接口来参数化地图的值。

Example: 例:

private static Map<String, Consumer<String>> MAP = new HashMap<>();
static {
    MAP.put("USE_CASE_ONE", (s) -> {/*TODO something with param s*/});
    // etc.
}

... then somewhere else: ...然后在其他地方:

public void handle(String key, String param) {
        // TODO check key exists
        MAP.get(key).accept(param);
}

What happens here is that for each given key set entry, you map it with a function that consumes a String (your param ). 在这里发生的是,对于每个给定的键集条目,都使用消耗String (您的param )的函数对其进行映射。

Then, you invoke the Consumer 's accept on your given param in one line. 然后,在一行中调用给定参数上的Consumeraccept

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM