2

我设置了一个循环属性更改侦听器。我有 2 个 A 类对象。我让一个对象监听另一个对象的变化,反之亦然。这是代码:

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CyclicPCLTest {

    public static class A implements PropertyChangeListener{
       private PropertyChangeSupport propertyChangeSupport;
       private String date;

        public A(String date) {
            this.date = date;
            propertyChangeSupport=new PropertyChangeSupport(this);
        }

        public String getDate() {
           return date;
       }

       public void setDate(String date) {
           String oldDate=this.date;
           this.date = date;
           propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, "date", oldDate, this.date));
       }

        public void addPropertyChangeListener(PropertyChangeListener listener){
            propertyChangeSupport.addPropertyChangeListener(listener);
        }

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            setDate ((String) evt.getNewValue());
        }
    }


    public static void main(String[] args) {
        List<A> as= Arrays.asList(new A[]{new A("01/02/2011"), new A("01/02/2011")});
        as.get(0).addPropertyChangeListener(as.get(1));
        as.get(1).addPropertyChangeListener(as.get(0));

        as.get(0).setDate("02/02/2011");
        System.out.println("date of the other A "+as.get(1).getDate());

        as.get(1).setDate("03/02/2011");
        System.out.println("date of the other A "+as.get(0).getDate());
    }
}

代码有效,这是输出:

date of the other A 02/02/2011
date of the other A 03/02/2011

我想知道它是怎么做的?它不应该给我一个stackoverflow错误吗?当第一个 A 更新时,它会通知第二个 A,然后第二个 A 会更新并通知第一个 A。这应该永远持续下去。

4

1 回答 1

2

那是因为只有在不等于firePropertyChange才会触发事件oldValuenewValue

2次递归运行后,当代码到达

propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, "date", oldDate, this.date));

和本质上变得相同(即)oldDate并且它不会将事件传播给侦听器this.dateoldDate.equals(this.date) == true

检查firePropertyChange方法的文档

将现有的 PropertyChangeEvent 触发到任何已注册的侦听器。如果给定事件的旧值和新值相等且非空,则不会触发任何事件。

于 2013-06-28T11:35:11.930 回答