【问题标题】:Java8 pass a method as parameter using lambdaJava8 使用 lambda 将方法作为参数传递
【发布时间】:2015-11-11 14:10:54
【问题描述】:

我想创建一个类来存储方法引用列表,然后使用 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);
        }
    }
}

这是我为测试创建的类

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 时出现问题。

怎么了?

【问题讨论】:

  • But there is something wrong when I pass this::aMethod - 这是因为某处有错误。如果您想要更具体的答案 - 请提出更具体的问题。
  • 发布您遇到的具体错误和更具体的问题
  • A Function 接受一个参数并有一个返回值。 aMethod 两者都没有。
  • 我该如何管理没有参数也没有返回值的方法?
  • 如果在某些时候你想使用Function(在java.util.function包中定义)确保提供类型参数,如Function&lt;String,Integer&gt;(或其他)。这里的示例使用 Function 原始类型,这将有效地禁用类型推断。

标签: java methods lambda java-8 parameter-passing


【解决方案1】:

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

【讨论】:

  • 您不需要stream() 来运行所有元素。就listOfMethodsToExecute.forEach(Runnable::run);
【解决方案2】:

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

me.addFunction(this::aMethod);

您需要引用一个实例或定义您的 Function 来获取一个 Test 对象。

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

me.addFunction(Test::aMethod);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 2017-12-31
    • 2018-10-26
    • 2010-11-16
    相关资源
    最近更新 更多