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

折月煮酒 提交于 2019-12-25 01:38:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!