测试Java Bean是否具有PropertyChangeSupport

时间:2012-05-22 17:14:34

标签: java events javabeans

是否有标准或最佳实践方法来了解POJO(普通旧Java对象)是否具有PropertyChangeSupport?

2 个答案:

答案 0 :(得分:1)

  

是否有标准或最佳实践方法来了解POJO(平原   旧Java对象)有PropertyChangeSupport吗?

PropertyChangeSupport类通常用于在bean类中实现实现属性更改支持,所以我怀疑你真正想知道的是,是否有办法查看bean是否存在class支持注册PropertyChangeListeners

采用以下示例bean类:

class Bean {

    private String name;
    private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        String oldName = this.getName();
        this.name = name;
        this.pcs.firePropertyChange("name", oldName, name);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.removePropertyChangeListener(listener);
    }
}

您可以使用Introspector类来查询bean并确定它是否提供了属性更改侦听器的注册,例如:

boolean supportsPropertyChangeListener = false;

BeanInfo info = Introspector.getBeanInfo(Bean.class);
EventSetDescriptor[] descriptors = info.getEventSetDescriptors();

for (EventSetDescriptor descriptor : descriptors) {
    if (descriptor.getListenerType().equals(PropertyChangeListener.class)) {
        supportsPropertyChangeListener = true;
    }
}

System.out.println(supportsPropertyChangeListener);

答案 1 :(得分:0)

我无法想到标准方法,但一种方法是使用反射并迭代类的属性,以查看是否有PropertyChangeSupport类型。

例如:

Field[] fields = clazz.getDeclaredFields();

for(Field field : fields) {
   if(field. getType().equals(PropertyChangeSupport.class)) {
      //do whatever you have to do
   }
}