Generating Java Bean setters in Eclipse

2020-06-21 04:38发布

问题:

We use Java beans on some projects where I work, this means a lot of handcrafted boilerplate code like this.

I'm after an Eclipse plugin, or a way of configuring Eclipse code templates that allows a developer to generate the setters from a simple skeleton class, in a similar fashion to the 'Generate Getters and Setters' does for POJOs.

Input

public class MyBean {
    private String value;
}

Expected output

 public class MyBean {
     private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

     private String value;

     public String getValue() {
         return this.value;
     }

     public void setValue(String newValue) {
         String oldValue = this.value;
         this.value = newValue;
         this.pcs.firePropertyChange("value", oldValue, newValue);
     }

     [...]
 }

I'm aware of project Lombok, but I'd prefer to stick to a pure Java/Eclipse based approach.

I'm considering writing an Eclipse plugin for this myself, what would be really useful is a more powerful template plugin in Eclipse, that could solve this problem and others.

回答1:

Here's a simple solution that uses the Eclipse code templates. This response is based on this answer which also provides a template for setting up the PropertyChangeSupport. I've simply provided additional details regarding the setup process.

In Eclipse, select Windows > Preferences > Java > Editor > Templates > New. Add the following code template using an unambiguous name, e.g. BeanProperty:

private ${Type} ${property};

public ${Type} get${Property}() {
    return ${property};
}

public void set${Property}(${Type} ${property}) {
    ${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}

Now, simply type BeanProperty in your target class, press Ctrl+Space to show the Template Proposals, and select the BeanProperty template. You can cycle through the field type, field name, and getter/setter names using your tab key. Press Enter to apply your changes.

See the Using Code Templates Help entry for more details, and this question for additional, useful code templates. Of course, this solution is still bound by the limitations of the Eclipse, and a more powerful plugin akin to the auto getter/setter tool would be desirable.