Reputation: 133
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.
Upvotes: 1
Views: 515
Reputation: 89254
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());
}
}
Upvotes: 3
Reputation: 4535
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.
Upvotes: 2