英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论