java 方法当参数_如何在Java 8中将方法作为参数传递?

我不明白如何使用lambdas将方法作为参数传递.

考虑以下(不编译)代码,如何完成它以使其工作?

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 listStuff,MethodParameter method) {

for (Stuff stuff : listStuff) {

System.out.println(method(stuff));

}

}

public DumbTest() {

List 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();

}

}


版权声明:本文为weixin_39548490原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。