簡體   English   中英

我可以通過數組調用方法嗎?

[英]Can I call a method through an array?

例如,我想創建一個具有調用方法指針的數組。 這就是我想說的:

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

如果我的描述性不夠或格式錯誤,我很抱歉。 感謝您的投入。

正如@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(); 運行該方法。

你可以制作Runnable數組。 在java中,使用Runnable代替函數指針[C]或委托[C#](據我所知)

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

(實例)

您也可以創建一個方法數組並調用每個方法,這可能更接近您在問題中請求的方法。 這是代碼:

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

唯一需要注意的是, number()必須公開,以便getMethod()可以找到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM