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
Java 8 pass method as parameter
提问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.function
such 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; Runnable
will 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 作为方法传递。