Java如何侦听bean的属性更改事件?
在此示例中,我们将监听bean的属性更改事件。我们创建一个名为的小beanMyBean,添加属性和getter/setter。我们想知道或在bean属性名称更改时得到通知。
首先,我们需要在PropertyChangeSupportBean中添加一个字段,使用该对象将触发属性更改事件。当我们需要倾听更改时,我们必须创建一个实现PropertyChangeListener。在此示例中,我们仅将MyBean类用作侦听器。
该PropertyChangeListener有一个名为方法propertyChange,并且此方法中,我们将执行代码来获取触发的事件由PropertyChangeSupport。
package org.nhooo.example.bean; import java.beans.PropertyChangeSupport; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.io.Serializable; public class MyBean implements PropertyChangeListener, Serializable { private Long id; private String name; private PropertyChangeSupport pcs = new PropertyChangeSupport(this); public MyBean() { pcs.addPropertyChangeListener(this); } /** * This method gets called when a bound property is changed. * * @param evt A PropertyChangeEvent object describing the event source * and the property that has changed. */ public void propertyChange(PropertyChangeEvent evt) { System.out.println("Name = " + evt.getPropertyName()); System.out.println("Old Value = " + evt.getOldValue()); System.out.println("New Value = " + evt.getNewValue()); } public static void main(String[] args) { MyBean bean = new MyBean(); bean.setName("My Initial Value"); bean.setName("My New Value"); bean.setName("My Yet Another Value"); } //〜---------------------------------------------Bean的Getter和Setter public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { String oldValue = this.name; this.name = name; //触发属性更改事件 pcs.firePropertyChange("name", oldValue, name); } }