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?
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.
You can use Fast Code Eclipse Plugin to do this pretty easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With