当尝试采用使用匿名或嵌套类实现侦听器的风格时,以便隐藏除侦听之外的其他用途的通知方法(即我不希望任何人能够调用actionPerformed)。例如来自java动作监听器:实现与匿名类 https://stackoverflow.com/questions/21631641/java-action-listener-implements-vs-anonymous-class?lq=1:
public MyClass() {
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//doSomething
}
});
}
问题是是否有一种优雅的方法可以使用这个习惯用法再次删除监听器?我发现实例化ActionListener
并不是每次都会产生相同的对象Collection.remove()
不会删除最初添加的对象。
为了被认为是平等的,听众应该具有相同的外部 this。要实现 equals,我需要为另一个对象获取外部 this 。所以它会像这样(我觉得有点笨拙):
interface MyListener {
Object getOuter();
}
abstract class MyActionListener extends ActionListener
implement MyListener {
}
public MyClass() {
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// doSomething on MyClass.this
}
public Object getOuter() {
return MyClass.this;
}
public boolean equals(Object other)
{
if( other instanceof MyListener )
{
return getOuter() == other.getOuter();
}
return super.equals(other);
});
}
}
或者我是否会被迫将 ActionListener 对象保留为外部类的(私有)成员?
将您的匿名侦听器分配给私有局部变量,例如
public MyClass() {
private Button myButton = new Button();
private ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//doSomething
}
};
private initialize() {
myButton.addActionListener(actionListener);
}
}
稍后您可以使用私有变量actionListener
再次删除它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)