ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 是否在lambda表达式中实例化了一个类?

2019-07-05 13:12:13  阅读:264  来源: 互联网

标签:java lambda functional-interface


参见英文答案 > What is a Java 8 Lambda Expression Compiled to?                                     1个
我有以下方法调用,其中我传递一个lambda表达式.是否在这里隐式实例化了一个类?

printStudents(
    roster,
    (Student s) -> s.getGender() == Student.Sex.MALE
        && s.getAge() >= 18
        && s.getAge() <= 25
);

方法签名:

printStudents(List<Student> roster, CheckStudent checkstudet)
interface CheckStudent {
    boolean test(Student s);
}

编辑

有些人建议我重构代码,但同样的问题出现了.

CheckStudent checkStudent = (Student s) -> s.getGender() == Student.Sex.MALE && s.getAge() >= 18 && s.getAge() <= 25;

是否在作业的右侧实例化了一个班级(我不是指学生班级)?

解决方法:

lambda表达式的值是对类实例的引用.所以,实际上,是的,正在创建一个类的实例.看看文档说的内容:

At run time, evaluation of a lambda expression is similar to
evaluation of a class instance creation expression, insofar as normal
completion produces a reference to an object.

但是,除了我们可以“看到”之外还有更多.引擎盖下有许多优化.根据某些因素,例如,可以再次使用先前创建的对象.这意味着不需要在lambda表达式的每个评估上分配新对象.我们来看看文档:

Evaluation of a lambda expression is distinct from execution of the
lambda body. Either a new instance of a class with the properties below is
allocated and initialized, or an existing instance of a class with the
properties below is referenced.

[…]

These rules are meant to offer flexibility to implementations of the
Java programming language, in that:

  • A new object need not be allocated on every evaluation.

  • Objects produced by different lambda expressions need not belong to different classes (if the bodies are identical, for example).

  • Every object produced by evaluation need not belong to the same class (captured local variables might be inlined, for example).

  • If an “existing instance” is available, it need not have been created at a previous lambda evaluation (it might have been allocated
    during the enclosing class’s initialization, for example).

您可能已经注意到,这是一个复杂的主题.有关更深入的理解,请参阅TheJava®语言规范,第“15.27.4. Run-time Evaluation of Lambda Expressions”章.

标签:java,lambda,functional-interface
来源: https://codeday.me/bug/20190705/1387705.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有