How do I list property names of a Bean?

package org.kodejava.bean;

import java.io.Serializable;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.IntrospectionException;

public class Fruit implements Serializable {
    private Long id;
    private String name;
    private String latinName;
    private double price;

    public Fruit() {
    }

    public static void main(String[] args) {
        try {
            BeanInfo bi = Introspector.getBeanInfo(Fruit.class);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();

            for (PropertyDescriptor pd : pds) {
                String propertyName = pd.getName();

                System.out.println("propertyName = " + propertyName);
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLatinName() {
        return latinName;
    }

    public void setLatinName(String latinName) {
        this.latinName = latinName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

The output of the code snippet above are:

propertyName = class
propertyName = id
propertyName = latinName
propertyName = name
propertyName = price

How do I create an instance of a Bean?

package org.kodejava.bean;

import java.io.Serializable;
import java.io.IOException;
import java.beans.Beans;

public class TheBean implements Serializable {
    private Long id;
    private String name;

    public TheBean() {
    }

    public static void main(String[] args) {
        try {
            TheBean bean = (TheBean) Beans.instantiate(
                    ClassLoader.getSystemClassLoader(), "org.kodejava.bean.TheBean");
            bean.setId(1L);
            bean.setName("John");
            System.out.println("The Bean = " + bean);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "[id=" + id + "; name=" + name + "]";
    }
}

How do I listen for a constrained property change?

The constrained property change is fired when a bean’s value is about to change. When a VetoableChangeListener veto the value change the bean’s value will be rolled-back to the previous value. In this example we have a constrained property called interest.

package org.kodejava.bean;

import java.beans.VetoableChangeSupport;
import java.beans.PropertyVetoException;

public class VetoBean {
    private double interest;

    private final VetoableChangeSupport vcs = new VetoableChangeSupport(this);

    public VetoBean() {
        vcs.addVetoableChangeListener(new VetoChangeListener());
    }

    public void setInterest(double interest) {
        try {
            vcs.fireVetoableChange("interest", this.interest, interest);

            this.interest = interest;
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        VetoBean bean = new VetoBean();
        bean.setInterest(10.99);
        bean.setInterest(15.99);

        // PropertyVetoException will be thrown because the interest value
        // should not exceed 20.00.
        bean.setInterest(20.99);
    }
}
package org.kodejava.bean;

import java.beans.VetoableChangeListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;

public class VetoChangeListener implements VetoableChangeListener {
    /**
     * This method gets called when a constrained property is changed.
     *
     * @param evt a `PropertyChangeEvent` object describing the
     *            event source and the property that has changed.
     * @throws java.beans.PropertyVetoException
     *          if the recipient wishes the property
     *          change to be rolled back.
     */
    public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
        String eventName = evt.getPropertyName();
        if (eventName.equalsIgnoreCase("interest")) {
            double interest = (Double) evt.getNewValue();
            if (interest > 20.00) {
                throw new PropertyVetoException("Interest must be below 20.00", evt);
            }
            System.out.println("Interest applied = " + interest);
        }
    }
}

How do I listen for bean’s property change event?

In this example we’ll listen to bean’s property change event. We create a small bean named MyBean, adds attributes and getter/setter. We want to know or to get notified when the bean property name is changed.

First we need the add a PropertyChangeSupport field to the bean, with this object we will fire the property change event. When we need to listen for the change we have to create an implementation of a PropertyChangeListener. In this example we’ll just use the MyBean class as the listener.

The PropertyChangeListener has a method called propertyChange and inside this method we’ll implement the code to get the event fired by the PropertyChangeSupport.

package org.kodejava.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 final 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's Getters and Setters

    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;

        // Fires a property change event
        pcs.firePropertyChange("name", oldValue, name);
    }
}

How do I prevent bean’s property being serialized to XML?

package org.kodejava.bean;

import java.beans.*;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class BeanToXmlTransient {
    private Long id;
    private String itemName;
    private String itemColour;
    private Integer itemQuantities;

    static {
        try {
            // In this block will change the attribute type of the 
            // itemQuantities to transient, so it will be not serialized 
            // to xml when we use XMLEncode to convert the bean to xml 
            // persistence.
            BeanInfo bi = Introspector.getBeanInfo(BeanToXmlTransient.class);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : pds) {
                if (propertyDescriptor.getName().equals("itemQuantities")) {
                    propertyDescriptor.setValue("transient", Boolean.TRUE);
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BeanToXmlTransient bean = new BeanToXmlTransient();
        bean.setId(1L);
        bean.setItemName("T-Shirt");
        bean.setItemColour("Dark Red");
        bean.setItemQuantities(100);

        try {
            XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                    new FileOutputStream("BeanTransient.xml")));

            // Write an XML representation of the specified object to the 
            // output.
            encoder.writeObject(bean);
            encoder.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public String getItemColour() {
        return itemColour;
    }

    public void setItemColour(String itemColour) {
        this.itemColour = itemColour;
    }

    public Integer getItemQuantities() {
        return itemQuantities;
    }

    public void setItemQuantities(Integer itemQuantities) {
        this.itemQuantities = itemQuantities;
    }
}

Here will see the the itemQuantities property is not serialized to XML.

<?xml version="1.0" encoding="UTF-8"?>
<java version="17" class="java.beans.XMLDecoder">
 <object class="org.kodejava.bean.BeanToXmlTransient">
  <void property="id">
   <long>1</long>
  </void>
  <void property="itemColour">
   <string>Dark Red</string>
  </void>
  <void property="itemName">
   <string>T-Shirt</string>
  </void>
 </object>
</java>