Java Bean、BeanUtils 和布尔包装类

Java Beans, BeanUtils, and the Boolean wrapper class(Java Bean、BeanUtils 和布尔包装类)

本文介绍了Java Bean、BeanUtils 和布尔包装类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using BeanUtils to manipulate Java objects created via JAXB, and I've run into an interesting issue. Sometimes, JAXB will create a Java object like this:

public class Bean {
    protected Boolean happy;

    public Boolean isHappy() {
        return happy;
    }

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

以下代码可以正常工作:

The following code works just fine:

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

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

However, attempting to get the happy property like so:

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 调用工作.但是,我没有这个选项,因为这些是生成的类.我假设发生这种情况是因为 Java Bean 库只考虑一个 is<name> 方法来表示一个属性,如果返回类型是原始 boolean,而不是包装器类型 <代码>布尔值.有没有人建议如何通过 BeanUtils 访问这些属性?我可以使用某种解决方法吗?

Changing everything to a primitive boolean allows both the set and get call to work. I don't have this option, however, since these are generated classes. I assume this happens because the Java Bean libraries only consider an is<name> method to represent a property if the return type is a primitive boolean, and not the wrapper type Boolean. Does anyone have a suggestion as to how to access properties like these through BeanUtils? Is there some kind of workaround I can use?

推荐答案

终于找到了法律确认:

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

8.3.2 Boolean properties

In addition, for boolean properties, we allow a getter method to match the pattern:

公共布尔值是<PropertyName>();

来自JavaBeans 规范.您确定没有遇到 JAXB-131 错误吗?

From JavaBeans specification. Are you sure you haven't came across JAXB-131 bug?

这篇关于Java Bean、BeanUtils 和布尔包装类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java Bean、BeanUtils 和布尔包装类

基础教程推荐