Java8使用lambda将方法作为参数传递

use*_*526 5 java methods lambda parameter-passing java-8

我想创建一个存储方法引用列表的类,然后使用Java 8 Lambda执行所有这些,但是我遇到了一些问题.

这是班级

public class MethodExecutor {
    //Here I want to store the method references
    List<Function> listOfMethodsToExecute = new LinkedList<>();

    //Add a new function to the list
    public void addFunction(Function f){
       if(f!=null){
            listOfMethodsToExecute.add(f);
       }
    }

    //Executes all the methods previously stored on the list
    public void executeAll(){
        listOfMethodsToExecute.stream().forEach((Function function) -> {
            function.apply(null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我为测试创建的类

public class Test{
    public static void main(String[] args){
        MethodExecutor me = new MethodExecutor();
        me.addFunction(this::aMethod);
        me.executeAll();    
    }

    public void aMethod(){
        System.out.println("Method executed!");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我通过this::aMethod使用时出现了问题me.addFunction.

怎么了?

Tag*_*eev 4

您应该提供一个合适的功能接口,其抽象方法签名与您的方法引用签名兼容。在你的情况下,似乎应该使用Runnable而不是:Function

public class MethodExecutor {
    List<Runnable> listOfMethodsToExecute = new ArrayList<>();

    //Add a new function to the list
    public void addFunction(Runnable f){
       if(f!=null){
            listOfMethodsToExecute.add(f);
       }
    }

    //Executes all the methods previously stored on the list
    public void executeAll(){
        listOfMethodsToExecute.forEach(Runnable::run);
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,静态main方法中this未定义。也许你想要这样的东西:

me.addFunction(new Test()::aMethod);
Run Code Online (Sandbox Code Playgroud)

  • 您不需要“stream()”来运行所有元素。只是 `listOfMethodsToExecute.forEach(Runnable::run);` (2认同)