【问题标题】:Surprised that removeChangeListener(null) doesn't throw NullPointerException惊讶于 removeChangeListener(null) 不会抛出 NullPointerException
【发布时间】:2017-09-04 12:58:04
【问题描述】:
public class Test {
public static void main(String[] args) {
try{
JTabbedPane tab = new JTabbedPane();
tab.removeChangeListener(null);
}catch(Exception e){
e.printStackTrace();
}
}
}
这不会产生NullPointerException。
当我打电话给tab.removeChangeListener(null) 时会发生什么?
【问题讨论】:
标签:
java
swing
null
changelistener
【解决方案1】:
当我调用 tab.removeChangeListener(null) 时到底发生了什么?
正是这个:
在JTabbedPane中调用了这个方法:
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
listenerList 被声明为protected EventListenerList listenerList = new EventListenerList();
而remove方法是:
public synchronized <T extends EventListener> void remove(Class<T> t, T l) {
if (l ==null) {
// In an ideal world, we would do an assertion here
// to help developers know they are probably doing
// something wrong
return;
}
...
...
因此,删除 null 只是返回,而不会影响侦听器