在java中创建字符串到任意函数的映射

时间:2017-07-23 14:04:21

标签: java

例如,我想支持以下功能:

FunctionActivator ac = new FunctionActivator();
ac.addFunc("times2", (Double x)->x*2));
ac.addFunc("reverse", (String s)-> new StringBuffer(s).reverse().toString());
Integer res = ac.useFunc("times2", 2); // should be 4

我采取的方法是这样的:

Interface F<R,P> {
    R apply(P input);
}

Class FunctionActivator {
    HashSet<String, /*don't know what to put here*/> keyToFunc;
    ...rest of implementation
}

如果我想保持FunctionActivator类非泛型,我应该在hashset值中添加什么类型?

1 个答案:

答案 0 :(得分:-1)

对我来说,它的工作原理如下:

public class FunctionActivator {

    //Use a HashMap for Key value mapping, Not a HashSet
    private HashMap<String, Function> keyToFunc = new HashMap<>();

    public void addFunc(String name, Function f) {
        keyToFunc.put(name, f);
    }

    public Object useFunc(String name, Object parameter) {
        return keyToFunc.get(name).apply(parameter);
    }
}

并使用它:

FunctionActivator ac = new FunctionActivator();

Function<Double, Double> doubleDoubleFunction = (Double x) ->x*2;
ac.addFunc("times2",doubleDoubleFunction);
//ac.addFunc("square", (Integer i) -> i*i); //This DOES NOT work, you need to cast to (Function<Integer, Integer>)

ac.addFunc("reverse", (Function<String, String>)(String s)->new StringBuffer(s).reverse().toString());

System.out.println(ac.useFunc("times2",new Double(5.0)));   // Prints 10.0
System.out.println(ac.useFunc("reverse","Hello World"));    // Prints dlroW olleH

此外,您不需要F界面,因为Function Interface存在相同且更多的方法