Does Java bean's setter permit return this?

后端 未结 10 559
一向
一向 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:48

    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.

提交回复
热议问题