“这个”参考在施工过程中逃脱了吗?
如果我做以下,
final class FooButton extends JButton{ FooButton(){ super("Foo"); addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ // do stuff } }); } }
我让this
引用隐含地逃脱了吗?
是的,因为在匿名内部类中,您可以像这样访问它:
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 } }); } }
原则上可以调用匿名ActionListener
的代码,并在FooButton
对象完全初始化之前使用FooButton
。
是的,此引用转义给侦听器。 因为这个监听器不是真正的外部类,所以我认为它没有任何问题。
在这里你可以看到这个逃脱:
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"); } }
是的, ActionListener
的匿名内部类具有对此的引用。
是。 封闭类的this
隐式地存在于非静态匿名类中。