java - function name as a string -
i trying wrap head around generic , functions... trying achieve: passing function name string executed:
i want wrapper.usefunction("eleven")
or wrapper.usefunction("ten")
public class wrapper<t> { public f usefunction(function<f, f> function) { return function.apply(f); } function<f, string> ten = s -> "10"; function<f, string> eleven = s -> "11"; }
but code not close compiling. maybe doesn't make sense. suggestions?
if have finite set of functions able call recommend building map maps strings instances of runnable (or similar functional interfaces). usefunction method may function implementation in map , call if exists.
example:
public class someclass { private final map<string, runnable> methods = new hashmap<>(); { methods.put("helloworld", () -> { system.out.println("hello world!"); }); methods.put("test", () -> { system.out.println("test!"); }); methods.put("dostuff", () -> { system.out.println("dostuff!"); }); } public void perform(string code) { methods.getordefault(code, () -> { system.err.println("no such method: "+code); }) .run(); } }
if want call arbitrary methods should use reflection stated others.
wiki
Comments
Post a Comment