在Eclipse中生成Java Bean setter



我们在我工作的一些项目中使用Javabean,这意味着有很多手工制作的样板代码。

我正在寻找一个Eclipse插件,或者一种配置Eclipse代码模板的方法,该方法允许开发人员从一个简单的骨架类中生成setter,其方式与POJO的"generate Getters and setters"类似。

输入

public class MyBean {
    private String value;
}

预期输出

 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);
     }
     [...]
 }

我知道Lombok项目,但我更愿意坚持纯基于Java/Eclipse的方法。

我正在考虑自己为此编写一个Eclipse插件,真正有用的是在Eclipse中提供一个更强大的模板插件,它可以解决这个问题和其他问题。

这里有一个使用Eclipse代码模板的简单解决方案。该响应基于该答案,该答案还提供了用于设置PropertyChangeSupport的模板。我只是简单地提供了有关设置过程的其他详细信息。

在Eclipse中,选择Windows>Preferences>Java>Editor>Templates>New。使用明确的名称添加以下代码模板,例如BeanProperty:

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

现在,只需在目标类中键入BeanProperty,按Ctrl+Space显示Template Proposals,然后选择BeanProperty模板。您可以使用tab键在字段类型、字段名称和getter/setter名称之间循环。按Enter应用您的更改。

有关更多详细信息,请参阅"使用代码模板帮助"条目,有关其他有用的代码模板,请参阅此问题。当然,这个解决方案仍然受到Eclipse的限制,需要一个类似于autogetter/setter工具的更强大的插件。

最新更新