在Java中,执行/运行期间的lambda是否会创建匿名类?

huangapple go评论64阅读模式
英文:

Do lambdas in Java create anonymous class during execution/runtime?

问题

在Java SE8规范中写道:“对lambda表达式的求值会产生函数式接口的实例”。

到目前为止,我理解的是 - lambda表达式会创建一个实现函数式接口的匿名类

有人能详细解释一下,我们编写的lambda表达式在运行时发生了什么吗?

英文:

In Java SE8 specification it is written: "Evaluation of a lambda expression produces an instance of a functional interface".

So far, my understanding is - lambda expression creates some anonymous class that implements a functional interface

Can someone explain in details, what happens in runtime with the lamda expressions that we write?

答案1

得分: 1

不,他们不这样做。

关于运行时如何表示lambda函数的确切机制是有意保留不明确的。

你只知道你会得到一个实现了必要接口/行为的有效对象。但除此之外很少有具体规定。规范甚至不会告诉你调用两次是否会产生相同的对象。

这种模糊的规范是为了使编译器和/或运行时能够在不违反规范的情况下进行优化。

与匿名类的关系更多是历史性的:如果你想做lambda所做的事情,但又不想使用lambda,那么匿名类是你的次佳工具。

英文:

No, they don't.

The exact mechanism on how the runtime represents lambdas is intentionally left under-specified.

All you know is that you'll get a valid object that implements the necessary interfaces/behaviours. But beyond that very little is specified. The spec doesn't even tell you if two calls to that will produce the same object or not.

This vague specification is done so that the compiler and/or the runtime can make optimizations without running afoul of the spec.

The relation with anonymous classes is more a historical one: if you wanted to do what lambdas do without using lambdas, then anonymous classes are your next-best tool.

huangapple
  • 本文由 发表于 2020年9月21日 22:46:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63994680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定