通常,当您希望对象被垃圾收集时,您应该将删除引用作为您的工作。这是在垃圾收集环境中管理内存的一部分。
只是,例如:
class MyInternalFrame extends JInternalFrame implements ActionListener {
...
void removeSelfAndDispose() {
for(JMenuItem button : parent.getMenuItems())
button.removeActionListener(this);
dispose();
}
}
但是,最好避免存储这些持久引用。例如,使用static
嵌套类而不是在容器上实现侦听器。
可以使用WeakReference
来构造一个不会阻止垃圾收集的侦听器,例如:
class MyInternalFrame extends JInternalFrame {
...
MyInternalFrame() {
for(JMenuItem button : parent.getMenuItems())
button.addActionListener(new WeakListener(this, button));
}
static class WeakListener implements ActionListener {
final Reference<JInternalFrame> ref;
final AbstractButton button;
WeakListener(JInternalFrame frame, AbstractButton button) {
ref = new WeakReference<JInternalFrame>(frame);
this.button = button;
}
@Override
public void actionPerformed(ActionEvent ae) {
JInternalFrame frame = ref.get();
if(frame == null) {
button.removeActionListener(this);
return;
}
...
}
}
}
但这是粗略的,不应依赖。我们无法控制垃圾收集何时运行,因此这样做可能会导致不可预知的行为。(我们保留引用的对象仍然存在,并在您认为它已被删除后响应事件。)
简单地防止不需要的引用被放置或在适当的时候故意删除它们更可靠。