从数组中调用方法

时间:2013-02-02 03:56:53

标签: java arrays methods call

Java中有没有办法从数组中调用方法?我想设计一个原始的棋盘游戏,我想用一系列方法来表示游戏空间。

2 个答案:

答案 0 :(得分:2)

也许你需要使用某种Command模式,比如

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

你可以添加尽可能多的实现,只要它们实现Cell接口 - board就可以执行它们。

答案 1 :(得分:1)

这是基本思路(命令模式)

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

输出

method-1

或使用反射

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