Does Java bean's setter permit return this?

后端 未结 10 554
一向
一向 2020-12-06 10:02

can I define setter method to return this rather than void?

Like:

ClassA setItem1() {
      return this;
}

ClassA setItem2() {
      return this;
}
         


        
10条回答
  •  北海茫月
    2020-12-06 10:53

    The Builder pattern is generally used for constructing immutable objects. Even though JavaBeans by nature aren't immutable, I have frequently used the builder pattern on my JavaBeans because it provides a fluent interface that I can use in my tests. The two are easily compatible with each other without breaking the JavaBean specification. You can check out it out on Stack Overflow at Builder Pattern in Effective Java

    You just need to make sure you include a default constructor as well as the private Builder constructor, and then put your standard getters and setters in the JavaBean object.

    This is much cleaner than constructor chaining, and easier to read as well.

提交回复
热议问题