问题
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);
}
回答1:
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);
}
来源:https://stackoverflow.com/questions/26203660/how-to-create-list-filled-with-methods-in-java-and-iterate-over-it-using-method