如果在构造函数中使用lambda,则使用"this"引用转义 [英] 'this' reference escape in case of lambda in constructor
问题描述
关于这个问题-
如果我们用lambda替换匿名类,或者方法引用引用了为什么以及如何执行此代码?
If we replace the anonymous class with the lambda or the method reference why and how this code is going to behave?
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(e -> doSomething(e));
}
}
推荐答案
原始问题中的代码
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
是有问题的,因为该对象已在构造函数中注册,然后可能在事件管理系统未完全构建的情况下被使用.实际上,仅当doSomething
访问ThisEscape
实例外部的内容时,这才是危险的.
is problematic because the object have been registered in the constructor and then may be used by the event managing system while not being fully constructed. In fact, this is dangerous only if doSomething
access something external to the ThisEscape
instance.
这与您的lambda等效"
And this is the same with your lambda "equivalent"
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(e -> doSomething(e));
}
}
但不要上当,匿名内部类并不严格等同于lambdas....this
指的是匿名内部类的当前实例,但指代lambda的封闭实例(this
是在lambda的关闭中):
But don't be fooled, anonymous inner classes are not strictly equivalent to lambdas... this
refers to the current instance in case of anonymous inner class but refers to the enclosing instance of the lambda (this
is in the closure of the lambda) :
interface doable {
public void doIt();
}
public class Outer {
public Outer() {
doable d1 = new doable() {
public void doIt() {
System.out.println(this);
}
};
d1.doIt();
doable d2 = ()->System.out.println(this);
d2.doIt();
}
public static void main(String []argv) {
new Outer();
}
}
产生类似:
Outer$1@3764951d
Outer@3cd1a2f1
第二行清楚地表明,lambda不是任何类的实例,也不是对象.
The second line clearly shows that a lambda is not an instance of any class, it is not an object.
这篇关于如果在构造函数中使用lambda,则使用"this"引用转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!