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

欢迎访问我的博客shammgodyoung

原文: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()]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值