1

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?

7
  • 1
    Look up reflection. Commented Aug 22, 2017 at 16:32
  • I saw example with reflections. Isn't there way to do that with java 8 without reflections? Commented Aug 22, 2017 at 16:33
  • It would not be wise to waste time trying. Reflection was built for this. Commented Aug 22, 2017 at 16:34
  • @PutinasPiliponis No. The only way to call function using string with function name, is the use of reflection. Commented Aug 22, 2017 at 16:35
  • 3
    if you don't want to use reflection, you can replace String with your own enum class. for example: wrapper.use(ELEVEN) Commented Aug 22, 2017 at 16:37

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.