hasanghaforian
hasanghaforian

Reputation: 14022

Automatically create builder for class in Eclipse

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 menu, a plugin or something else. I could not find anything under "Refactor".

Upvotes: 51

Views: 39829

Answers (5)

Khanna111
Khanna111

Reputation: 3913

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

Edit: After 5 years, revisiting this topic, would recommend to use lombok that has become industry standard anyway and is also IDE agnostic ==> would work if your team mates use a variety of IDEs. Check out this annotation. You could also include pattern inheritance among classes.

@Builder(toBuilder = true)
// or you could use this for inheritance
@SuperBuilder

Upvotes: 22

Christoph
Christoph

Reputation: 4000

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

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

Upvotes: 17

Atmega
Atmega

Reputation: 131

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;
}
}

Upvotes: 3

jaco
jaco

Reputation: 544

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.

Upvotes: 29

unique_ptr
unique_ptr

Reputation: 586

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

Upvotes: 2

Related Questions