我有一個循環屬性更改監聽器設置。我有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.這應該永遠持續下去。
你有沒有調試和測試? – sanbhat