如果我这样做,
final class FooButton extends JButton{
FooButton(){
super("Foo");
addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
// do stuff
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我让this引用隐含地逃脱了吗?
是的,此引用转义给侦听器.由于这个监听器实际上并不是一个外部类,所以我认为它没有任何问题.
在这里你可以看到这个逃脱:
final class FooButton extends JButton{
Foo(){
super("Foo");
addActionListener(new ActionListener(){
private buttonText = FooButton.this.getText(); // empty string
@Override
public void actionPerformed(ActionEvent e){
// do stuff
}
});
this.setText("Hello");
}
}
Run Code Online (Sandbox Code Playgroud)
是的,因为在匿名内部类中,您可以像这样访问它:
final class FooButton extends JButton {
Foo() {
super("Foo");
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FooButton button = FooButton.this;
// ... do something with the button
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
ActionListener原则上可以调用匿名代码并FooButton在FooButton对象完全初始化之前使用.