gpt4 book ai didi

java - 从匿名类到 lambda 表达式

转载 作者:行者123 更新时间:2023-12-01 21:36:17 25 4
gpt4 key购买 nike

下面使用匿名类时,我们调用变量x没有问题

interface Age { 
int x = 21;
void getAge();
}

class AnonymousDemo {
public static void main(String[] args) {
Age oj1 = new Age() {
@Override
public void getAge() {
// printing age
System.out.print("Age is "+x);
}
};
oj1.getAge();
}
}

但是当我将相同的代码与下面的 lambda 表达式一起使用时,发生了异常:

interface Age { 
int x = 21;
void getAge();
}

class AnonymousDemo {
public static void main(String[] args) {
Age oj1 = () -> { System.out.print("Age is "+x); };
oj1.getAge();
}
}

这里会出现什么问题?知道lambda表达式只是实现匿名类的缩写。

最佳答案

实际上,lambda 表达式并不是“只是实现匿名类的缩写”。使用 lambda 表达式的好处是它可以直接访问 this 类的实例(调用它的类),而匿名类则不能(它有自己的 this实例)。

In other words, anonymous classes introduce a new scope. so that names are resolved from their superclasses and interfaces and can shadow names that occur in the lexically enclosing environment. For lambdas, all names are resolved lexically.

https://stackoverflow.com/a/22640484还有

Lambda performance with Anonymous classes

When application is launched each class file must be loaded and verified.

Anonymous classes are processed by compiler as a new subtype for the given class or interface, so there will be generated a new class file for each.

Lambdas are different at bytecode generation, they are more efficient, used invokedynamic instruction that comes with JDK7.

For Lambdas this instruction is used to delay translate lambda expression in bytecode untill runtime. (instruction will be invoked for the first time only)

As result Lambda expression will becomes a static method(created at runtime). (There is a small difference with stateles and statefull cases, they are resolved via generated method arguments)

https://stackoverflow.com/a/33874965

例如:

interface Supplier {
void foo();
}

class A {

private String name;

public void doSome() {
baz(() -> System.out.println(this.name));
}

private void baz(Supplier sup){
sup.foo();
}
}

class A {

private String name;

public void doSome() {
baz(new Supplier() {
void foo() {
System.out.println(A.this.name);
}
});
}

private void baz(Supplier sup){
sup.foo();
}
}

我建议阅读:Java8 Lambdas vs Anonymous classes .

关于java - 从匿名类到 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61921589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com