Java 在 Eclipse 中自动为类创建构建器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29493898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatically create builder for class in Eclipse
提问by hasanghaforian
Is there a way to use an automatic builderto create builder (Joshua Bloch's Builder Pattern) for classes in Eclipse
? For example an option in the menu, a plugin or something else. I could not find anything under "Refactor
".
有没有办法使用自动构建器为 中的类创建构建器(Joshua Bloch 的构建器模式)Eclipse
?例如菜单中的选项、插件或其他东西。我在“ Refactor
”下找不到任何内容。
采纳答案by Khanna111
Maybe I am late to the party.
也许我参加聚会迟到了。
Eclipse on its own does not provide a way to generate code to support builder pattern. However it can be extended through plugins to enhance the functionality.
Eclipse 本身不提供生成代码以支持构建器模式的方法。但是,它可以通过插件进行扩展以增强功能。
There is this plugin that I use this:
有这个插件,我用这个:
回答by unique_ptr
You could add your own template window -> preferences -> java -> editor -> templates and this will be activated with the content proposal but not by refactor action
您可以添加自己的模板窗口 -> 首选项 -> java -> 编辑器 -> 模板,这将通过内容提案激活,但不会通过重构操作激活
回答by jaco
You may want to look at lombokannotations to generate builders without the boiler plate code. For example:
您可能希望查看lombok注释以生成没有样板代码的构建器。例如:
@Builder
public class MyPojo {
private String name;
}
MyPojoBuilder.builder().name("yourame").build();
The limitation is that this doesn't seem to work with abstract classes.
限制是这似乎不适用于抽象类。
回答by Atmega
Try https://github.com/vojtek/write-it-once
试试https://github.com/vojtek/write-it-once
package ${cls.package.name};
public class ${cls.shortName}Builder {
public static ${cls.name}Builder builder() {
return new ${cls.name}Builder();
}
<% for(field in cls.fields) {%>
private ${field.type.name} ${field.name};
<% } %>
<% for(field in cls.fields) {%>
public ${cls.name}Builder ${field.name}(${field.type.name} ${field.name}) {
this.${field.name} = ${field.name};
return this;
}
<% } %>
public ${cls.name} build() {
final ${cls.name} data = new ${cls.name}();
<% for(field in cls.fields) {%>
data.${field.setter.name}(this.${field.name});
<% } %>
return data;
}
}
回答by Christoph
I currently use Spark Builder Generatorwith Eclipse Neon.1a Release (4.6.1) and it works well.
我目前在 Eclipse Neon.1a Release (4.6.1) 中使用Spark Builder Generator,它运行良好。