Reputation: 39
I want to be able to create list (collection, array) filled with my own methods and in each step of iteration call the method. What's the best solution for this?
I want something like this:
List a = new List();
a.add(myCustomMethod1());
a.add(myCustomMethod2());
Object o = new Object();
for (Method m : a){
m(o);
}
Upvotes: 2
Views: 10273
Reputation: 124
In Java 8 and above you can create a List of Functional Interfaces to store the methods, as the following example shows:
// Create a list of Consumer
List<Consumer<String>> methodList= new ArrayList<>();
// Store the methods in the list
methodList.add(p -> method1(p));
methodList.add(p -> method2(p));
methodList.add(p -> method3(p));
methodList.forEach(f -> f.accept("Hello"));
Functions with no arguments you can use Runnable:
List<Runnable> methods = new ArrayList<>();
methods.add(() -> method1());
methods.add(() -> method2());
methods.add(() -> method3());
methods.forEach(f -> f.run());
Upvotes: 7
Reputation: 234857
In Java, you can do this with reflection by making a list of Method
objects. However, an easier way is to define an interface for objects that have a method that takes an Object
argument:
public interface MethodRunner {
public void run(Object arg);
}
List<MethodRunner> a = new ArrayList<>();
a.add(new MethodRunner() {
@Override
public void run(Object arg) {
myCustomMethod1(arg);
}
});
a.add(new MethodRunner() {
@Override
public void run(Object arg) {
myCustomMethod2(arg);
}
});
Object o = new Object();
for (MethodRunner mr : a) {
mr.run(o);
}
Upvotes: 3