Search code examples
javaeclipseeclipse-templates

Eclipse template for setter that calls firePropertyChange()


For MVC model classes, my setters look like:

enum BoundProperty {FIELD_NAME, ...}

private Type fieldName;

public setFieldName(Type newValue) {
    Type oldValue = fieldName;
    fieldName = newValue;
    firePropertyChange(BoundProperty.FIELD_NAME, oldValue, newValue);
}

Given a field, can this output be produced from the autogenerated setter? If not is there a way to get this output from a template?

The output should CamelCase the field name to produce the method name, so fieldName generates setFieldName() and Uppercase the field name to produce the property enum.

So fieldName generates FIELD_NAME (or FIELDNAME would work too).


Solution

  • I think there is not a straightforward way to make this through Eclipse templates, mainly regarding the camelCase/upperCase and generation of enum values. You can check these two questions Is there a way to capitalize the first letter of a value of a variable in Eclipse (Helios) code templates, Programmatically add code templates? to dig into further details.

    IMHO, the best way to achieve what you want is to use the Fast Code Eclipse Plugin and write a velocity template for that plugin that generates all the code from the fields.

    enum BoundProperty {
    #foreach ($field in ${fields})
        ${field.toUpperCase()} #if( $foreach.hasNext ), #end
    #end
    }
    
    #foreach ($field in ${fields})
        public ${field.type} get${field.name.substring(0,1).toUpperCase()}${field.name.substring(1)}(${field.type} newValue) {
            Type oldValue = fieldName;
            fieldName = newValue;
            firePropertyChange(BoundProperty.${field.name.toUpperCase()}, oldValue, newValue);       
        }
    #end
    

    Or change the "getter_setter" template of that plugin.