开发者

Custom eclipse template to make setter return this object?

开发者 https://www.devze.com 2023-02-09 17:37 出处:网络
I ne开发者_如何学编程ed to custom eclipse setter template to return this object, like this public Person setName(String name){

I ne开发者_如何学编程ed 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.


As far as I can tell, all you can do is edit the "Window->Preferences->Java->Code Style->Code->Setter body" template in Java like so:

${field} = ${param};
return this;

While this will not automatically set the return type for you, Eclipse does throw a red squiggly at you for every one of your setters, which you can then hover over and select "Change method return type to 'yourTypeHere'".

0

精彩评论

暂无评论...
验证码 换一张
取 消