Hermes Trismegistus
Hermes Trismegistus

Reputation: 525

Calling methods from an array

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.

Upvotes: 0

Views: 419

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

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

Upvotes: 1

jdevelop
jdevelop

Reputation: 12296

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.

Upvotes: 2

Related Questions