加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 06:04:23 所属栏目:Java 来源:网络整理
导读:我不明白如何使用lambdas将方法作为参数传递. 考虑以下(不编译)代码,如何完成它以使其工作? public class DumbTest { public class Stuff { public String getA() { return "a"; } public String getB() { return "b"; } } public String methodToPassA(Stu
我不明白如何使用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<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();

    }
}

解决方法

声明您的方法接受与您的方法签名匹配的现有功能接口类型的参数:
public void operateListWith(List<Stuff> listStuff,Function<Stuff,String> method) {
    for (Stuff stuff : listStuff) {
        System.out.println(method.apply(stuff));
    }
}

并称之为:

operateListWith(listStuff,this::methodToPassA);

作为进一步的见解,您不需要方法toTassA的间接:

operateListWith(listStuff,Stuff::getA);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读