can I define setter method to return this rather than void?
Like:
ClassA setItem1() {
return this;
}
ClassA setItem2() {
return this;
}
I would guess this is not in violation of the JavaBean specification, although I am not sure of it.
Check out the following example:
public class JavaBean {
private String value;
public String getValue() {
return value;
}
public JavaBean setValue(String value) {
this.value = value;
return this;
}
public static void main(String[] args) throws Exception {
JavaBean bean = new JavaBean();
JavaBean.class.getMethod("setValue", String.class).invoke(bean, "test");
System.out.println(bean.getValue());
}
}
Many frameworks access JavaBeans using the reflection API. As you can see above, accessing a settter which returns 'this' is not influenced by the return type (the return type is not used to locate a method via reflection). It also makes sense, because you cannot have two methods in one scope that are identical except for their return type.