2014-09-20 58 views
3

例如,我想创建一个具有指向某个方法的指针的数组。 这就是我想说的:我可以通过数组调用一个方法吗?

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

对不起,如果我不是不够,或者如果我的格式是错误的描述。感谢您的输入。

+3

创建一个像Runnable这样的接口的数组(或列表)并执行'array [i] .run()'。 – 2014-09-20 01:23:01

回答

0

您可以制作Runnable的数组。在Java中,Runnable来代替函数指针[C]或代表[C#](据我所知)

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

(live example)

+2

要改进这个答案,请考虑演示lambda语法。 – 2014-09-20 01:31:45

+0

@JeffreyBosboom哦,谢谢。我仍然是最近java的新生> o < – ikh 2014-09-20 01:34:26

+0

我对Java很新,但是要像其他任何数组一样初始化Runnable数组? – AnotherNewbie 2014-09-20 02:15:55

0

你可以可选地创建一个方法阵列和调用每个方法,该方法可能会更接近你在你的问题中所要求的。下面是代码:

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

唯一要注意的是,要进行号()有市民因此它可以通过getMethod()被发现。

1

由于@ikh的回答,您的array应该是Runnable[]

Runnable是定义run()方法的接口。

然后,您可以初始化数组,后者调用一个方法如下:

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(); 

由于Java 8中,您可以使用LAMDA表达式写一个简单的功能接口实现。所以你的阵列可以被初始化:

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

然后,您仍然可以使用array[1].run();运行的方法。

+0

由于Java约定建议变量名称应以小写字母开头,因此我将变量名称从'Array'更改为'array'。 – ericbn 2014-09-20 03:38:46

相关问题