Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and call method from a HashMap

I have 2 files: ImplementationProvider and CaseHandler.

ImplementationProvider:

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

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? 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.

like image 439
i712345 Avatar asked Oct 12 '25 17:10

i712345


1 Answers

If you are using Java 8, you can lever the Consumer functional interface to parametrize your map's values with.

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).

Then, you invoke the Consumer's accept on your given param in one line.