【问题标题】:Can I call a method through an array?我可以通过数组调用方法吗?
【发布时间】:2014-11-14 15:52:18
【问题描述】:

例如,我想创建一个数组,其中包含调用方法的指针。 这就是我想说的:

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

如果我的描述性不够或者我的格式有误,我很抱歉。感谢您的意见。

【问题讨论】:

  • 创建一个类似 Runnable 接口的数组(或列表)并执行array[i].run()

标签: java arrays methods call


【解决方案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(); 来运行该方法。

【讨论】:

  • 我将变量名从 Array 更改为 array,因为 Java 约定建议变量名应以小写字母开头。
【解决方案2】:

您也可以创建一个方法数组并调用每个方法,这可能更接近您在问题中所要求的。代码如下:

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() 可以找到它。

【讨论】:

    【解决方案3】:

    您可以创建Runnable 的数组。在java中,使用Runnable代替函数指针[C]或委托[C#](据我所知)

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

    (live example)

    【讨论】:

    • 要改进此答案,请考虑演示 lambda 语法。
    • @JeffreyBosboom 哦,谢谢。我还是最近java的大一学生>o
    • 我是 Java 新手,但要像初始化其他数组一样初始化 Runnable 数组吗?
    猜你喜欢
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 2014-08-03
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多