在 Eclipse 中生成 Java 个 Bean setter
Generating Java Bean setters in Eclipse
我们在我工作的一些项目中使用 Java beans,这意味着很多像这样的手工制作的样板代码。
我想要一个 Eclipse 插件,或者一种配置 Eclipse 代码模板的方法,它允许开发人员从一个简单的框架 class 以类似于 'Generate Getters and Setters' 的方式生成 setter为 POJO 做。
输入
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 中,select Windows > 首选项 > Java > 编辑器 > 模板 > 新建。使用明确的名称添加以下代码模板,例如BeanProperty
:
private ${Type} ${property};
public ${Type} get${Property}() {
return ${property};
}
public void set${Property}(${Type} ${property}) {
${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}
现在,只需在目标 class 中键入 BeanProperty
,按 Ctrl+Space
显示模板建议,然后 select BeanProperty
模板。您可以使用 tab
键循环显示字段类型、字段名称和 getter/setter 名称。按 Enter
应用您的更改。
有关其他有用的代码模板,请参阅 Using Code Templates Help entry for more details, and this question。当然,这个解决方案仍然受到 Eclipse 的限制,并且需要一个更强大的类似于 auto getter/setter 工具的插件。
我们在我工作的一些项目中使用 Java beans,这意味着很多像这样的手工制作的样板代码。
我想要一个 Eclipse 插件,或者一种配置 Eclipse 代码模板的方法,它允许开发人员从一个简单的框架 class 以类似于 'Generate Getters and Setters' 的方式生成 setter为 POJO 做。
输入
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 中,select Windows > 首选项 > Java > 编辑器 > 模板 > 新建。使用明确的名称添加以下代码模板,例如BeanProperty
:
private ${Type} ${property};
public ${Type} get${Property}() {
return ${property};
}
public void set${Property}(${Type} ${property}) {
${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}
现在,只需在目标 class 中键入 BeanProperty
,按 Ctrl+Space
显示模板建议,然后 select BeanProperty
模板。您可以使用 tab
键循环显示字段类型、字段名称和 getter/setter 名称。按 Enter
应用您的更改。
有关其他有用的代码模板,请参阅 Using Code Templates Help entry for more details, and this question。当然,这个解决方案仍然受到 Eclipse 的限制,并且需要一个更强大的类似于 auto getter/setter 工具的插件。