Search code examples
javaarraysmethodscall

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.


Solution

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