Java 8 传递方法作为参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25186216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:49:27  来源:igfitidea点击:

Java 8 pass method as parameter

javalambdajava-8method-reference

提问by Torsten R?mer

Currently getting into Java 8 lambda expressions and method references.

目前正在研究 Java 8 lambda 表达式和方法引用。

I want to pass a method with no args and no return value as argument to another method. This is how I am doing it:

我想将一个没有 args 且没有返回值的方法作为参数传递给另一个方法。这就是我的做法:

public void one() {
    System.out.println("one()");
}

public void pass() {
    run(this::one);
}

public void run(final Function function) {
    function.call();
}

@FunctionalInterface
interface Function {
    void call();
}

I know there is a set of predefined functional interfaces in java.util.functionsuch as Function<T,R>but I didn't find one with no arguments and not producing a result.

我知道有一组预定义功能接口的java.util.function,如Function<T,R>,但我没有找到一个不带任何参数,而不是产生结果。

采纳答案by Joop Eggen

It really does not matter; Runnablewill do too.

这真的没有关系;Runnable也会做。

Consumer<Void>,
Supplier<Void>,
Function<Void, Void>

回答by obey

You can also pass lambda like this:

你也可以像这样传递 lambda:

public void pass() {
    run(()-> System.out.println("Hello world"));
}

public void run(Runnable function) {
    function.run();
}

In this way, you are passing lambda directly as method.

通过这种方式,您直接将 lambda 作为方法传递。