Java Bean,BeanUtils和Boolean包装类

时间:2011-03-10 22:10:00

标签: java jaxb javabeans apache-commons-beanutils

我正在使用BeanUtils来操作通过JAXB创建的Java对象,我遇到了一个有趣的问题。有时,JAXB会创建一个这样的Java对象:

public class Bean {
    protected Boolean happy;

    public Boolean isHappy() {
        return happy;
    }

    public void setHappy(Boolean happy) {
        this.happy = happy;
    }
}

以下代码可以正常使用:

Bean bean = new Bean();
BeanUtils.setProperty(bean, "happy", true);

但是,尝试获取happy属性是这样的:

Bean bean = new Bean();
BeanUtils.getProperty(bean, "happy");

此例外的结果:

Exception in thread "main" java.lang.NoSuchMethodException: Property 'happy' has no getter method in class 'class Bean'

将所有内容更改为原始boolean允许set和get调用都能正常工作。但是,我没有这个选项,因为这些是生成的类。我假设发生这种情况是因为如果返回类型是原始is<name>而不是包装类型boolean,Java Bean库只考虑Boolean方法来表示属性。有没有人建议如何通过BeanUtils访问这些属性?我可以使用某种解决方法吗?

3 个答案:

答案 0 :(得分:10)

最后我找到了法律确认:

  

8.3.2布尔属性

     

此外,对于布尔属性,我们允许getter方法匹配模式:

     

public boolean is<PropertyName>();

来自 JavaBeans规范。你确定你没有遇到JAXB-131 bug吗?

答案 1 :(得分:6)

使用BeanUtils处理布尔isFooBar()案例的解决方法

  1. 创建新的BeanIntrospector

  2. private static class BooleanIntrospector implements BeanIntrospector{
        @Override
        public void introspect(IntrospectionContext icontext) throws IntrospectionException {
            for (Method m : icontext.getTargetClass().getMethods()) {
                if (m.getName().startsWith("is") && Boolean.class.equals(m.getReturnType())) {
                    String propertyName = getPropertyName(m);
                    PropertyDescriptor pd = icontext.getPropertyDescriptor(propertyName);
    
                    if (pd == null)
                        icontext.addPropertyDescriptor(new PropertyDescriptor(propertyName, m, getWriteMethod(icontext.getTargetClass(), propertyName)));
                    else if (pd.getReadMethod() == null)
                        pd.setReadMethod(m);
    
                }
            }
        }
    
        private String getPropertyName(Method m){
            return WordUtils.uncapitalize(m.getName().substring(2, m.getName().length()));
        }
    
        private Method getWriteMethod(Class<?> clazz, String propertyName){
            try {
                return clazz.getMethod("get" + WordUtils.capitalize(propertyName));
            } catch (NoSuchMethodException e) {
                return null;
            }
        }
    }
    

    1. 注册BooleanIntrospector:

      BeanUtilsBean.getInstance()。getPropertyUtils()。addBeanIntrospector(new BooleanIntrospector());

答案 2 :(得分:0)

你可以用SET - sufix创建第二个getter作为解决方法:)