AnotherNewbie
AnotherNewbie

Reputation: 25

Can I call a method through an array?

For example, I want to create an array that have pointers to call a method. This is what I'm trying to say:

import java.util.Scanner;

public class BlankSlate {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter a number.");
        int k = kb.nextInt();

         Array[] = //Each section will call a method };
         Array[1] = number();

         if (k==1){
             Array[1]; //calls the method
         }
    }

    private static void number(){
        System.out.println("You have called this method through an array");
    }
}

I'm sorry if I'm not being descriptive enough or if my formatting is wrong. Thank you for your inputs.

Upvotes: 3

Views: 1283

Answers (3)

ericbn
ericbn

Reputation: 10948

As @ikh answered, your array should be a Runnable[].

Runnable is an interface that defines a run() method.

You can then initialize your array and latter call a method as follows:

Runnable[] array = new Runnable[ARRAY_SIZE];

// as "array[1] = number();" in your "pseudo" code
// initialize array item
array[1] = new Runnable() { public void run() { number(); } };

// as "array[1];" in your "pseudo" code
// run the method
array[1].run();

Since Java 8, you can use a lamda expression to write a simpler functional interface implementation. So your array can be initialized with:

// initialize array item
array[1] = () -> number();

You'll then still use array[1].run(); to run the method.

Upvotes: 1

You could alternatively create a method array and invoke each method, which would perhaps be closer to what you requested in your question. Here is the code:

public static void main(String [] args) {
    try {
        // find the method
        Method number = TestMethodCall.class.getMethod("number", (Class<?>[])null);

        // initialize the array, presumably with more than one entry
        Method [] methods = {number};

        // call method through array
        for (Method m: methods) {
            // parameter is null since method is static
            m.invoke(null);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } 
}


public static void number(){
    System.out.println("You have called this method through an array");
}

The only caveat is that number() had to be made public so it could be found by getMethod().

Upvotes: 0

ikh
ikh

Reputation: 10417

You can make array of Runnable. In java, Runnable is used instead of function pointer[C] or delegates[C#] (as far as I know)

Runnable[] arr = new Runnable[] {
    new Runnable() { public void run() { number(); } }
};
arr[0].run();

(live example)

Upvotes: 0

Related Questions