简体   繁体   中英

How to make a hashmap of dynamic methods in Java

This is a bit of a specific question, but I want to know how to make a HashMap of functions that are obtained in parameters, like so:

//All functions will take in string and return void
public HashMap<String,Function> functions = new HashMap<String,Function>();
public void addMethod(String name, Function func){
   functions.put(name, func);
}
public void useMethod(String name, String input){
   functions[name](input);
}

How would I do this correctly?

You can use a Consumer<String> .

First, change your HashMap to:

public HashMap<String,Consumer<String>> functions = new HashMap<>();

then your addMethod to:

public void addMethod(String name, Consumer<String> func){
    functions.put(name, func);
}

then you useMethod to:

public void useMethod(String name, String input){
    functions.get(name).accept(input);
}

All functions will take in string and return void

In this situation, you can use a Consumer<String> interface and create a factory as follows:

public class ConsumerFactory {

    private static final Map<String, Consumer<String>> consumers = new HashMap<>();

    public static Consumer<String> getConsumer(String key) {
        if (key != null && consumers.containsKey(key)) {
            return consumers.get(key);
        }
        throw new NoSuchElementException(key);
    }

    public static Consumer<String> addConsumer(String key, Consumer<String> value) {
        return consumers.put(key, value);
    }
}

ConsumerFactory.addConsumer("print", System.out::println);
ConsumerFactory.getConsumer("print").accept("Hello");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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