Can I call a method through an array?
For example, I want to create an array with pointers to call a method. Here's 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 apologize if I am not well versed in the description, or if my formatting is incorrect. Thanks for your contributions.
As @ikh answered, yours array
should be Runnable[]
.
Runnable
is an interface that defines a method run()
.
Then you can initialize your array and the latter call the method like this:
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 the lamda expression to write a simpler implementation of a functional interface. This way your array can be initialized with:
// initialize array item
array[1] = () -> number();
Then you will use array[1].run();
to run the method.
You can create an array Runnable
. In java used Runnable
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)
You can also create an array of methods and call each method that would possibly 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 the number () must be public in order to be found using the getMethod () method.