Automatically create builder for class in Eclipse

后端 未结 5 674
离开以前
离开以前 2020-12-24 10:35

Is there a way to use an automatic builder to create builder (Joshua Bloch\'s Builder Pattern) for classes in Eclipse? For example an option in the men

相关标签:
5条回答
  • 2020-12-24 11:14

    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.

    There is this plugin that I use this:

    https://github.com/henningjensen/bpep

    0 讨论(0)
  • 2020-12-24 11:18

    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

    0 讨论(0)
  • 2020-12-24 11:29

    You may want to look at lombok annotations to generate builders without the boiler plate code. For example:

    @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.

    0 讨论(0)
  • 2020-12-24 11:31

    I currently use Spark Builder Generator with Eclipse Neon.1a Release (4.6.1) and it works well.

    • https://marketplace.eclipse.org/content/sparkbuildergenerator
    • https://github.com/helospark/SparkBuilderGenerator

    You can set the preferences under:
    Window->Preferences->Java->Spark Builder Generator

    0 讨论(0)
  • 2020-12-24 11:33

    Try 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;
    }
    }
    
    0 讨论(0)
提交回复
热议问题