简体   繁体   中英

Test if a Java Bean have PropertyChangeSupport

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

Is there are a standard or best practice way to know if a POJO (Plain Old Java Object) have PropertyChangeSupport?

The PropertyChangeSupport class is usually used to implement property change support in a bean class so I suspect that what you really want to know is if there is a way of seeing if a bean class supports registering PropertyChangeListeners .

Take the following example bean class:

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);
    }
}

You can use the Introspector class to query the bean and determine if it offers registration of property change listeners, something like this, for example:

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);

I can't think of a standard way, but one way would be to use reflection and iterate over your class's properties to see if any are of type PropertyChangeSupport .

For example:

Field[] fields = clazz.getDeclaredFields();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM