简体   繁体   English

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

[英]Java8 pass a method as parameter using lambda

I would like to create a class that store a list of methods references and then executes all of them using Java 8 Lambda but I have some problem. 我想创建一个存储方法引用列表的类,然后使用Java 8 Lambda执行所有这些,但是我遇到了一些问题。

This is the 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);
        }
    }
}

This is the class that I created for test 这是我为测试创建的类

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

But there is something wrong when I pass this::aMethod using me.addFunction . 但是当我使用me.addFunction传递this::aMethod时出现了问题。

What is wrong? 怎么了?

You should provide a suitable functional interface which abstract method signature is compatible with your method reference signature. 您应该提供一个合适的功能接口,抽象方法签名与您的方法参考签名兼容。 In your case it seems that Runnable instead of Function should be used: 在你的情况下,似乎应该使用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);
    }
}

Also note that in static main method this is not defined. 另请注意,在静态main方法中,未定义this方法。 Probably you wanted something like this: 可能你想要这样的东西:

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

You can't refer to this in a static context as there is no this 你不能在static上下文中引用this ,因为没有this

me.addFunction(this::aMethod);

You need to refer to an instance or define your Function to take a Test object. 您需要引用实例或定义函数以获取Test对象。

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

and

me.addFunction(Test::aMethod);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM