java—很惊讶removechangelistener(null)没有抛出nullpointerexception

4nkexdtk  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(542)
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) ?

g6baxovj

g6baxovj1#

调用tab.removechangelistener(null)时到底发生了什么?
正是这样:
在jtabbedpane中,调用此方法:

public void removeChangeListener(ChangeListener l) {
    listenerList.remove(ChangeListener.class, l);
}

在哪里 listenerList 声明为 protected EventListenerList listenerList = new EventListenerList(); 移除方法为:

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只是返回,而不影响侦听器

相关问题