【问题标题】:Calling methods from an array从数组中调用方法
【发布时间】:2013-01-17 11:32:30
【问题描述】:

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

【问题讨论】:

  • 您在数组上调用方法,然后将板单元传递给方法。

标签: java arrays methods call


【解决方案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);
}

【讨论】:

    【解决方案2】:

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

    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 就可以执行它们。

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 2015-02-12
      • 1970-01-01
      • 2020-02-26
      • 2017-08-14
      • 2019-11-02
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多