user477768
user477768

Reputation:

Java Bean Conventions

One of the conventions of Java Beans is:

The return type of the setter must be void.

Or at least that's what most people say. My question is: does it really HAVE TO be void? I like to return "this" instead of "void" since I can chain methods together like this:

student.setName("Tom").setAge(15);

If I return "this" instead of "void", will there be any problem with Spring container or Servlet container or whatever makes use of Java Beans?

Upvotes: 2

Views: 308

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122394

Yes, the return type of a setter must be void in order for java.beans.Introspector to recognise it as a bean property and return a PropertyDescriptor for it. APIs that just inspect the method names and argument types directly will work with non-void setters but anything that relies on the Introspector won't.

A good example of a workaround for this is the Amazon Web Services SDK, which provides both normal public void setSomething methods (to be a valid Java Bean) and also fluent public X withSomething methods that return this.

Student s = new Student().withName("Tom").withAge(15);

Upvotes: 4

Chris
Chris

Reputation: 33

To be sure, you can add another private method which return the object seted in your SET method and call this new method in public void set()

Upvotes: -2

Related Questions