例如,在匿名内部类的情况下,传递(匿名)对象引用并执行该对象的方法。
Lambda 是在需要时执行的代码块。
当遇到 lambda 时,JVM 会发生什么? JVM 将 lambdas 相关的代码块存放在哪里(Heap : Young, Old or Permanent Generation)?
我尝试搜索,我得到了使用 lambdas 的语法,但无法理解 JVM 内部发生了什么,因为在 JAVA 中一切都是基于对象的。
那么在 OOP 的上下文中,lambda 是如何工作的?
lambda 是否违反 OOP 概念?
Lambda 对垃圾收集器有好处吗,因为没有创建对象 不用担心内存问题和清除内存?
最佳答案
我不会浪费时间去思考 lambda 表达式是否违反了 OO 原则。它的目标是增加语言的能力,而不是编写 OO 代码,我看不出 lambdas 是如何违反封装、继承或多态性的。
这个 article解释 Java 如何处理 lambda 表达式:
What’s interesting about Lambda expressions is that from the JVM’s perspective they’re completely invisible. It has no notion of what an anonymous function or a Lambda expression is. It only knows bytecode which is a strict OO specification. It’s up to the makers of the language and its compiler to work within these constraints to create newer, more advanced language elements.
考虑以下代码:
List names = Arrays.asList("1", "2", "3");
Stream lengths = names.stream().map(name -> name.length());
... It begins quite simply by loading the names var and invokes its
.stream()
method, but then it does something quite elegant. Instead of creating a new object that will wrap the Lambda function, it uses the newinvokeDynamic
instruction which was added in Java 7 to dynamically link this call site to the actual Lambda function.
aload_1 //load the names var
// call its stream() func
invokeinterface java/util/List.stream:()Ljava/util/stream/Stream;
//invokeDynamic magic!
invokedynamic #0:apply:()Ljava/util/function/Function;
//call the map() func
invokeinterface java/util/stream/Stream.map:
(Ljava/util/function/Function;)Ljava/util/stream/Stream;
InvokeDynamic
is an instruction that was added in Java 7 to make the JVM less strict, and allows dynamic languages to bind symbols at run-time, vs. doing all the linkage statically when the code is compiled by the JVM.
Lambda 代码
aload_0
invokevirtual java/lang/String.length:()
invokestatic java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
areturn
关于Java Lambda : How it works in JVM & is it OOP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29143803/