Example 2

This example demonstrates how to extend templates with the java extend mechanism.

This example enhances the example-1. It uses a new template BoundAttrsBeanTemplate. The template extends the SimpleBeanTemplate and generates methods for property change support on each bean. Every setter method fires a property change event.

Look how the SimpleBeanTemplate supports the extensions.

How to start the example?

To start the example-2 go into the root-Directory "example" and start

    ant example-2

This should generate the bean into the src/java folder.

How does this work?

Enhancing the template

The example uses its own template for bean generation. It is programmed in the file bean/BoundAttrsBeanTemplate.java in the src/templates directory of the examples. If you take a look to the source you will see that it is derived from the template SimpleBeanTemplate.java from example 1.^

  ...
  public class BoundAttrsBeanTemplate extends SimpleBeanTemplate {
  ...

Than it overrides the two methods generateAttributeDeclaration() and generateGetterSetterPair(). The first method calls the super method to generate the normal attribute declarations and than it adds the attributes for the attributes needes for the bean support plus the add and remve methods for property change listener registration.

The second method replaces completely the generation of the setter and getter methods. The setters are generated to fire a property change event.

Changing the configuration file config.xml

The new template must be configured to be used for beans. This is done in the config.xml of the example. The only difference to the config.xml of example 1 is the line where you define the template. The new line looks like:

  ...
  <template name="BeanRoot" file="bean/BoundAttrsBeanTemplate.java"/>
  ...

This is the only difference.

The generated source

The new generated bean now looks like this:

//THIS CODE IS GENERATED
package example;

public class Person { 

    private String name;
    java.beans.PropertyChangeSupport propertyChangeSupport = new java.beans.PropertyChangeSupport(this);
    public void addPropertyChangeListener( PropertyChangeListener aListener ) {
      propertyChangeSupport.addPropertyChangeListener(aLister);
    }

    public void removePropertyChangeListener( PropertyChangeListener aListener ) {
      propertyChangeSupport.removePropertyChangeListener(aLister);
    }

    private void firePropertyChangedEvemt(String propertyName, Object oldValue, Object newValue) {
      propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
    }


    public Person() { 
        super();
    }
    public void setName( String value ) {
        firePropertyChangedEvemt("name", this.name, value);
        this.name = value;
    }

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

Just a few more lines of code.