Putinas Piliponis Putinas Piliponis - 2 months ago 15
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

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

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 you want to call arbitrary methods you should probably use Reflection as stated by others.