java - java中将方法作为参数传递

标签 java methods parameters

我正在做一个小方法,我需要传递一个方法作为参数,所以我不必重复代码。 所以我必须使用这个方法,唯一改变的是我在这个方法中使用的方法。因此,如果我可以在参数中传递一个方法,它将大大简化我的代码。 这是我的代码。我可以使用java的refletct吗?

public static void testsForLinkedLists(int potencia,
            int repeticoesteste, int somarAoArray, String ficheiroExcel,
            int validararray, Method pushMethod)

我有这两种方法,我想将其用作参数

public class measuring_tests {
    public static double timeToPushLinkedStack(int intendedPushes) {
        final LinkedStackOfStrings measuringTimeToPush = new LinkedStackOfStrings();
        final String element = "measuring_test";
        int numberOfPushesDone = 0;
        double totalPushTime = 0;
        Stopwatch stopwatch = new Stopwatch();

        while (numberOfPushesDone < intendedPushes) {

            measuringTimeToPush.push(element);

            numberOfPushesDone++;

        }
        totalPushTime = stopwatch.elapsedTime();

        while (measuringTimeToPush.size > 0) {
            measuringTimeToPush.pop();
        }

        return totalPushTime;

    }

    public static double timeToPopLinkedStack(int intendedPops) {

        final LinkedStackOfStrings measuringTimeToPop = new LinkedStackOfStrings();
        final String element = "measuring_test";

        while (measuringTimeToPop.size < intendedPops) {
            measuringTimeToPop.push(element);
        }

        double totalPopTime = 0;
        Stopwatch stopwatch = new Stopwatch();

        while (measuringTimeToPop.size > 0) {
            measuringTimeToPop.pop();
        }

        totalPopTime = stopwatch.elapsedTime();

        return totalPopTime;
    }

最佳答案

如果所有方法都具有相同的签名 double m(int),那么您可以使用类似 the IntToDoubleFunction interface 的内容。并传递方法引用:

public static void testsForLinkedLists(int potencia,
        int repeticoesteste, int somarAoArray, String ficheiroExcel,
        int validararray, IntToDoubleFunction pushMethod)

你可以这样调用它:

testsForLinkedLists(...., measuring_tests::timeToPushLinkedStack);

关于java - java中将方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43372745/

相关文章:

java - Sikuli 无法通过 Jenkins 在屏幕上找到图像

java - 在调用方法中为什么不抛出就可以捕获异常,为什么不抛出就不能捕获异常的子类

java - 如何将jlabel放置在jpanel中的特定位置

java - 访问修饰符继承: on abstract methods

java - Java 中温度程序的类声明

Swift:在初始化器中传递一个 func 作为参数

Java Jersey - 在同一个@path 上使用不同参数的相同方法?

java - lock.tryLock() 线程安全吗?

java - 无法访问 junit 测试类中的包私有(private)方法

javascript - 函数参数未定义 - Javascript