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

Java8 pass a method as parameter using lambda

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

这是class

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

这是我为测试

创建的class
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!");
    }
}

但是当我使用 me.addFunction 传递 this::aMethod 时出现问题。

怎么了?

您应该提供一个合适的功能接口,其抽象方法签名与您的方法引用签名兼容。在您的情况下,似乎应该使用 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);
    }
}

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

me.addFunction(new Test()::aMethod);

您不能在 static 上下文中引用 this,因为没有 this

me.addFunction(this::aMethod);

您需要引用一个实例或定义您的函数来获取一个测试对象。

public void addFunction(Function<Test, String> f){
   if(f!=null){
        listOfMethodsToExecute.add(f);
   }
}

me.addFunction(Test::aMethod);