Search code examples
javacollectionsiterator

How to create list filled with methods in Java and iterate over it (using methods)


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);
}

Solution

  • 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);
    }