如何在Java 8中将方法作为参数传递? [英] How do I pass a method as a parameter in Java 8?
本文介绍了如何在Java 8中将方法作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白如何使用lambdas将方法作为参数传递。
I don't understand how to use lambdas to pass a method as a parameter.
考虑以下(不编译)代码,如何将其完成为让它工作?
Considering the following (not compiling) code, how can I complete it to get it work ?
public class DumbTest {
public class Stuff {
public String getA() {
return "a";
}
public String getB() {
return "b";
}
}
public String methodToPassA(Stuff stuff) {
return stuff.getA();
}
public String methodToPassB(Stuff stuff) {
return stuff.getB();
}
//MethodParameter is purely used to be comprehensive, nothing else...
public void operateListWith(List<Stuff> listStuff, MethodParameter method) {
for (Stuff stuff : listStuff) {
System.out.println(method(stuff));
}
}
public DumbTest() {
List<Stuff> listStuff = new ArrayList<>();
listStuff.add(new Stuff());
listStuff.add(new Stuff());
operateListWith(listStuff, methodToPassA);
operateListWith(listStuff, methodToPassB);
}
public static void main(String[] args) {
DumbTest l = new DumbTest();
}
}
推荐答案
声明您的方法接受与您的方法签名匹配的现有功能接口类型的参数:
Declare your method to accept a parameter of an existing functional interface type which matches your method signature:
public void operateListWith(List<Stuff> listStuff, Function<Stuff, String> method) {
for (Stuff stuff : listStuff) {
System.out.println(method.apply(stuff));
}
}
并按原样调用:
operateListWith(listStuff, this::methodToPassA);
作为进一步的见解,您不需要间接 methodToPassA
:
As a further insight, you don't need the indirection of methodToPassA
:
operateListWith(listStuff, Stuff::getA);
这篇关于如何在Java 8中将方法作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文