我不明白如何使用 lambda 将方法作为参数传递。
考虑以下(未编译)代码,我怎样才能完成它以使其工作?
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();
}
}
最佳答案
声明您的方法以接受与您的方法签名匹配的现有功能接口(interface)类型的参数:
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
的间接访问:
operateListWith(listStuff, Stuff::getA);
关于java - 如何在 Java 8 中将方法作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32255681/