Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

design patterns - Does Java bean's setter permit return this?

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

Like:

ClassA setItem1() {
      return this;
}

ClassA setItem2() {
      return this;
}

then I can use new ClassA().setItem1().setItem2()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a lot of misunderstanding about JavaBeans spec.

The main reason for it's existence is the unified Java "component" model. It's a way to interact programatically with a Java Object using Reflection. The API itself is named JavaBeans Introspection. Please, take a look at example usages and You will know a lot more than an average Java programmer does.

Introspection API can be used to manipulate GUI elements in an unified manner. Your component exposes it's properties as a pairs of getters and setters so that they could be discovered and manipulated at run-time on a GUI builder's property sheet.

So, mixing fluent APIs and JavaBeans Spec in my opinion is a no-go. That's two completely unrelated concepts and can disrupt each other. JavaBeans Introspection might not work when method signature differs (return type).

Take a look at this example (taken from linked tutorial):

public class SimpleBean
{
private final String name = "SimpleBean";
private int size;

public String getName()
{
    return this.name;
}

public int getSize()
{
    return this.size;
}

public void setSize( int size )
{
    this.size = size;
}

public static void main( String[] args )
        throws IntrospectionException
{
    BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );
    for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
        System.out.println( pd.getName() );
}
}

This example creates a non-visual bean and displays following properties derived from the BeanInfo object:

  • class
  • name
  • size

You might want to see what happens when You change void return type to anything else. I have done so and the result is the same. So, does that mean it's allowed?

I'm afraid no. The JavaBeans spec is quite strict about those method signatures. It just happened that implementation is forgiving. Nonetheless, I'd disadvise mixing fluent interface with JavaBeans. You can't really rely that, if the discovery works now, it will also in future.

But, from the other side - it looks like You don't use JavaBeans to full extent. Only the getters/setters pair of method. It's up to You how You implement and design Your APIs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...