0
在Java中調用數組中的方法有沒有辦法?我想設計一個原始的棋盤遊戲,我想用一組方法來表示遊戲空間。從數組中調用方法
在Java中調用數組中的方法有沒有辦法?我想設計一個原始的棋盤遊戲,我想用一組方法來表示遊戲空間。從數組中調用方法
這是基本的想法(Command模式)
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);
}
也許你需要使用某種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
}
}
如你願意,你可以添加儘可能多的實現,只要它們實現電池接口 - 板可執行它們。
調用的陣列上的方法,則通過板小區方法。 – AlexWien