我们在我工作的一些项目中使用 Java bean,这意味着有很多像这样的手工制作的样板代码。
我正在寻找一个 Eclipse 插件,或者一种配置 Eclipse 代码模板的方法,它允许开发人员从一个简单的骨架类生成 setter,其方式类似于为 POJO 执行的“生成 Getters 和 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 代码模板的简单解决方案。此响应基于 this answer它还提供了用于设置 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
显示模板建议,然后选择 BeanProperty
模板。您可以使用 tab
键循环显示字段类型、字段名称和 getter/setter 名称。按 Enter
应用您的更改。
参见 Using Code Templates Help entry了解更多详情,以及 this question获取更多有用的代码模板。当然,这个解决方案仍然受到 Eclipse 的限制,并且需要一个更强大的类似于自动 getter/setter 工具的插件。
关于java - 在 Eclipse 中生成 Java Bean setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36673076/