Can Java store methods in arrays?

后端 未结 5 2119
生来不讨喜
生来不讨喜 2020-12-31 08:55

Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it\'d be a bit neater (and out of curiosity to see

5条回答
  •  生来不讨喜
    2020-12-31 09:50

    Yes, you can store methods in arrays using Reflection, however it is likely that what you actually want to do in this situation is use polymorphism.

    As an example of polymorphism in relation to your problem - say you created an interface as follows:

    public interface MoveCommand {
        void move();
    }
    

    You can then create implementations as follows:

    public class MoveLeftCommand implements MoveCommand {
        public void move() {
            System.out.println("LEFT");
        }
    }
    

    etc. for the other move options. You could then store these in an MoveCommand[] or collection like a List, and then iterate over the array/collection calling move() on each element, for example:

    public class Main {
    
        public static void main(String[] args) {
            List commands = new ArrayList();
            commands.add(new MoveLeftCommand());
            commands.add(new MoveRightCommand());
            commands.add(new MoveLeftCommand());
    
            for (MoveCommand command:commands) {
                command.move();
            }
        }
    
    }
    

    Polymorphism is very powerful, and the above is a very simple example of something called the Command Pattern. Enjoy the rest of your Wumpus World implementation :)

提交回复
热议问题