【问题标题】:Firing events in javajava中的触发事件
【发布时间】:2011-11-19 08:27:50
【问题描述】:

为什么 PropertyChangeSupport 类中的方法 firePropertyChange(String propertyName, Object oldValue, Object newValue) 不检查旧值和新值是否可以同时为空?

【问题讨论】:

  • 您的意思是“为什么firePropertyChange(String,Object,Object) 不处理两个对象都等于null 的情况,就像处理对象为Object#equals 的情况一样”?

标签: java javabeans


【解决方案1】:

PropertyChangeEvent javadoc 可能会提供一些线索:

可以为旧值和新值提供空值,如果它们 真实值未知。

一个事件源可以发送一个空对象作为名称来表明一个 如果其属性已更改,则任意设置。在这种情况下,旧 并且新值也应该为空。

所以看起来oldValue==nullnewValue==nullsource==null 也有一些特殊含义。因此,当两个值都是 nulls 时,可能希望始终传播更改,即使它们相同。

【讨论】:

    【解决方案2】:

    我不确定你是什么意思,但这里的实际代码肯定比我试图解释它更干净:)

    /**
         * Reports a bound property update to listeners
         * that have been registered to track updates of
         * all properties or a property with the specified name.
         * <p>
         * No event is fired if old and new values are equal and non-null.
         * <p>
         * This is merely a convenience wrapper around the more general
         * {@link #firePropertyChange(PropertyChangeEvent)} method.
         *
         * @param propertyName  the programmatic name of the property that was changed
         * @param oldValue      the old value of the property
         * @param newValue      the new value of the property
         */
        public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
            if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
                firePropertyChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue));
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-24
      • 2013-06-04
      • 1970-01-01
      • 2020-09-24
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多