javabean:boolean和Boolean类型的getter方法名是有区别的

原文:https://blog.csdn.net/10km/article/details/53924181

javaBean中,要设置或获取某个property的值,就需要相应的get和set方法,对于primitive和自定义类类型的属性(如:property),getter和setter方法就是getProperty和setProperty(第一个字母变大写,前面再加get或set)。对于类型为 boolean的属性(不是Boolean),getter方法还可以写为isProperty(getProperty仍然可用)。 
一般来我们用IDE(eclipse,JBuilder,IntelliJ IDEA)的自动生成代码功能为属性添加gettter/setter方法时,对于boolean类型,生成的getter方法名都是isProperty,而不是getProperty。 
所以对于boolean类的属性,如果有一天你把它手工改成了Boolean类型,那么就要把相应的getter方法名改为getProperty,否则isProperty方法不会被视为property的gettter方法,就会给后续带来一系列麻烦。 
下面是个简单的测试代码,原本是boolean类型的woman变量让我改成了Boolean,然后PropertyUtilsBean 就无法找到woman的getter方法了,如果改成getWoman,则不论woman是Boolean还是boolean都可以被正确识别。

package iadb;

import java.beans.PropertyDescriptor;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.junit.Test;

public class TestBeanUtils {
    public class Person{
        private Boolean woman;

        public Boolean isWoman() {
            return woman;
        }

        public void setWoman(Boolean woman) {
            this.woman = woman;
        }

        public Person(){
        }
    }
    @Test
    public void test() {
        BeanUtilsBean beanUtils = BeanUtilsBean.getInstance();
        PropertyUtilsBean propertyUtils = beanUtils.getPropertyUtils();
        PropertyDescriptor[] origDescriptors = propertyUtils.getPropertyDescriptors(Person.class);
        // 列出Person的所有属性及getter/setter方法
        for(PropertyDescriptor propertyDescriptor:origDescriptors){
            System.out.println(propertyDescriptor);
        }
    }

}
  • 输出,找不到readMethod

java.beans.PropertyDescriptor[name=woman; propertyType=class java.lang.Boolean; writeMethod=public void iadb.TestBeanUtils$Person.setWoman(java.lang.Boolean)] 
java.beans.PropertyDescriptor[name=class; propertyType=class java.lang.Class; readMethod=public final native java.lang.Class java.lang.Object.getClass()]


猜你喜欢

转载自blog.csdn.net/Dxx_23/article/details/81012997
今日推荐