要委托的Bean类写法。
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Date;
public class StudentBean {
private String name;
private int age;
private Date birthday;
//创建委托。
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public StudentBean() {
}
public StudentBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
String oldvalue = this.name;
this.name = name;
//激发帧听器。
pcs.firePropertyChange("name", oldvalue, this.name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
//加入帧听方法。
public void addPropertyChangeListener(PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
//加入移除帧听方法。
public void removePropertyChangeListener(PropertyChangeListener listener)
{
pcs.removePropertyChangeListener(listener);
}
}
测试代码:
import java.beans.IntrospectionException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class IntrospectorTest {
public static void main(String[] args)
{
try{
Class st = Class.forName("StudentBean");
Constructor<StudentBean> cct = st.getConstructor(null);
StudentBean sbean = cct.newInstance();
//注册帧听器。
sbean.addPropertyChangeListener(new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(evt.getPropertyName()+":"+evt.getOldValue()+":"
+evt.getNewValue());
}
} );
//内省获取Bean字段描述。
PropertyDescriptor pd = new PropertyDescriptor("name", StudentBean.class);
//开启对该字段的帧听。
pd.setBound(true);
Method namgget = pd.getWriteMethod();
namgget.invoke(sbean, "wangwu");
System.out.println(sbean.getName());
}catch(Exception e)
{
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号