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

参见英文答案 >
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”章.

点赞