Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom eclipse template to make setter return this object?

I need to custom eclipse setter template to return this object, like this

public Person setName(String name){
    this.name=name;
    return this;
}

but Java->Code Style->Templates only allow me to custom setter body part, not method definition. Is there any way to do it?

like image 414
secmask Avatar asked Feb 11 '11 04:02

secmask


2 Answers

I'm afraid I can't offer a solution to allow you to modify the Eclipse template for this, however can I suggest that you rethink what you're doing here?

If you check the JavaBeans spec you'll see that when you define your methods in this way they are no longer valid property setters. Setters should have a void return type; you may regret creating these non-standard beans in the long run. For instance, try using java.beans.Introspector to gather bean info for your class and you'll see that your property 'setters' are not found.

I know it's nice to be able to quickly initialise your beans with chained calls like:

new Person().setName("John Smith").setDateOfBirth(...).setAddress(...)

Can I suggest as an alternative you use standard setters (that return void) and instead introduce builder methods like:

public Person withName(String name) {
    this.setName(name);
    return this;
}

Your quick single line construction then looks like:

new Person().withName("John Smith").withDateOfBirth(...).withAddress(...)

I find the 'with' prefix reads nicely too.

like image 136
joelittlejohn Avatar answered Oct 11 '22 15:10

joelittlejohn


You can use Fast Code Eclipse Plugin to do this pretty easily.

like image 29
fastcodejava Avatar answered Oct 11 '22 13:10

fastcodejava