2014-09-20 88 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

相關問題