Putinas Piliponis Putinas Piliponis - 6 months ago 66
Java Question

function name as a string

I am trying to wrap my head around generic and functions... what I am trying to achieve: Passing function name as a string to get it executed:

I want to do


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 this code not even close to compiling. Maybe it doesn't make any sense. Any suggestions?

Answer Source

If you have a finite set of functions which you would like to be able to call I would recommend building a Map which maps Strings to instances of Runnable (or similar functional interfaces). Your useFunction method may then look up the function implementation in the Map and call it if it exists.


public class SomeClass {

    private final Map<String, Runnable> methods = new HashMap<>();
        methods.put("helloworld", () -> {
            System.out.println("Hello World!");
        methods.put("test", () -> {
        methods.put("doStuff", () -> {

    public void perform(String code) {
            () -> {
                System.err.println("No such Method: "+code);


If you want to call arbitrary methods you should probably use Reflection as stated by others.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download