gpt4 book ai didi

java - 内部类如何使这个引用转义

转载 作者:行者123 更新时间:2023-12-02 09:21:30 25 4
gpt4 key购买 nike

不合规的代码示例 "inner class" section

内部类中似乎没有调用实例方法,所以我不知道这个引用是如何在这段代码中转义的。

我读过一些问题,比如 this ,但它是不同的

public class DefaultExceptionReporter implements ExceptionReporter {
public DefaultExceptionReporter(ExceptionReporter er) {
er.setExceptionReporter(new ExceptionReporter() {
public void report(Throwable t) {
// report exception
}
public void setExceptionReporter(ExceptionReporter er) {
// register ExceptionReporter
}
});
}
// Default implementations of setExceptionReporter() and report()
}

最佳答案

DefaultExceptionReporter的构造函数中,您实例化一个匿名类。匿名类在父类完全实例化之前获取对其父类的引用。

如果父对象具有状态,则意味着匿名类理论上可以在其完全构造之前对其进行操作。

希望这表明了潜在的问题:

class DefaultExceptionReporter implements ExceptionReporter {

private final int foo;

public DefaultExceptionReporter(ExceptionReporter er) {
er.setExceptionReporter(new ExceptionReporter() {

{
System.out.println(DefaultExceptionReporter.this.foo);
}

public void report(Throwable t) {}
public void setExceptionReporter(ExceptionReporter er) {}
});
foo = 1;
}

// ...
}

即使foo是final的并且被赋值为1,这也会打印零。final变量最终有两个值,这通常是不可能的。

因为你的对象是无状态的,所以我认为这没什么大不了的。不过,您可能应该将该类声明为 final,因此无法扩展它并添加状态。

关于java - 内部类如何使这个引用转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663094/

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