1

i want to create an class which accept "function" and i can add there some method that i can call later. For example:

final Wrapper wrapper = new Wrapper();

wrapper.add(() -> System.out.println("Test"));
wrapper.add(() -> <something else>);
wrapper.add(() -> <something else>);

And later i can call it like:

wrapper.get(0).execute();

Is there any way using Function<?>

Thanks a lot.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101

2 Answers2

3

You can store a List of Runnable objects (if you don't need to return a value).

public class Wrapper {
    private final List<Runnable> runnables = new ArrayList<>();
    
    public void add(Runnable r) {
        runnables.add(r);
    }
    
    public Runnable get(int index) {
        return runnables.get(index);
    }
    
    public static void main(String[] args) {
        final Wrapper wrapper = new Wrapper();
        wrapper.add(() -> System.out.println("Test"));
        wrapper.get(0).run();
    }
}

If you want to return a value, you can use java.util.function.Supplier.

public class Wrapper {
    private final List<Supplier<?>> suppliers = new ArrayList<>();
    
    public void add(Supplier<?> s) {
        suppliers.add(s);
    }
    
    public Supplier<?> get(int index) {
        return suppliers.get(index);
    }
    
    public static void main(String[] args) {
        final Wrapper wrapper = new Wrapper();
        wrapper.add(() -> "Test");
        System.out.println(wrapper.get(0).get());
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

If you do not want to use Runnable for semantic reasons, you could create your own functional interface.

@FunctionalInterface
public interface Action {
    void execute();
}

Then, in your Wrapper class you'd have a method add(Action action). Since the method signature is the same as in your example you can leave your code as is:

wrapper.add(() -> System.out.println("Test"));

And in the end you can call wrapper.get(0).execute(); to call the wrapped method.

QBrute
  • 4,405
  • 6
  • 34
  • 40
  • 1
    This is the "classic" way of implementing "function pointers" in Java (e.g. for callbacks). Defining and implementing an interface (like in this example) is usually one of the *FIRST* design options I consider. IMHO... – paulsm4 Aug 17 '21 at 22:20