0

Is there a way in Java to call methods from an array? I want to design a primitive board game and I would like to use an array of methods to represent the game spaces.

1
  • you call methods on an array, you pass the board cell to the method. Commented Feb 2, 2013 at 3:58

2 Answers 2

2

perhaps you need to use some sort of Command pattern, like

class Board {
   Cell[][] cells = new Cell[5][5];

   void addCell(int i, int j, Cell cell) {
     cells[i,j] = cell;
   }

   void executeCell(int i, int j) {
     cells[i,j].execute(this);
   }
}

interface Cell {
   void execute(Board board);
}

class CellImpl implements Cell {
  void execute(Board board) {
    // do your stuff here
  }
}

you may add as much implementations as you wish, as soon as they implement Cell interface - board can execute them.

Sign up to request clarification or add additional context in comments.

Comments

1

This is the basic idea (Command pattern)

static Runnable[] methods = new Runnable[10];

public static void main(String[] args) throws Exception {
    methods[0] = new Runnable() {
        @Override
        public void run() {
            System.out.println("method-0");
        }
    };
    methods[1] = new Runnable() {
        @Override
        public void run() {
            System.out.println("method-1");
        }
    };
    ...
    methods[1].run();
}

output

method-1

or with reflection

static Method[] methods = new Method[10];

public static void method1() {
    System.out.println("method-1");
}

public static void method2() {
    System.out.println("method-2");
}

public static void main(String[] args) throws Exception {
    methods[0] = Test1.class.getDeclaredMethod("method1");
    methods[1] = Test1.class.getDeclaredMethod("method2");
    methods[1].invoke(null);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.