小编Cha*_*rom的帖子

Java Bean,BeanUtils和Boolean包装类

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

public class Bean {
    protected Boolean happy;

    public Boolean isHappy() {
        return happy;
    }

    public void setHappy(Boolean happy) {
        this.happy = happy;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下代码工作得很好:

Bean bean = new Bean();
BeanUtils.setProperty(bean, "happy", true);
Run Code Online (Sandbox Code Playgroud)

但是,试图获得这样的happy属性:

Bean bean = new Bean();
BeanUtils.getProperty(bean, "happy");
Run Code Online (Sandbox Code Playgroud)

此例外的结果:

Exception in thread "main" java.lang.NoSuchMethodException: Property 'happy' has no getter method in class 'class Bean'
Run Code Online (Sandbox Code Playgroud)

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

java jaxb javabeans apache-commons-beanutils

13
推荐指数
2
解决办法
7222
查看次数

使用BeanUtils设置List索引属性

我正在尝试使用BeanUtils与类似于以下内容的Java bean进行交互:

public class Bean {
    private List<Integer> prices = new LinkedList<Integer>();

    public List<Integer> getPrices() {
        return prices;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据BeanUtils文档,BeanUtils支持Lists的索引属性:

作为JavaBeans规范的扩展,BeanUtils包会考虑其基础数据类型为java.util.List(或List的实现)的任何属性.

但是,假设我尝试执行以下操作:

Bean bean = new Bean();

// Add nulls to make the list the correct size
bean.getPrices().add(null);
bean.getPrices().add(null);

BeanUtils.setProperty(bean, "prices[0]", 123);
PropertyUtils.setProperty(bean, "prices[1]", 456);

System.out.println("prices[0] = " + BeanUtils.getProperty(bean, "prices[0]"));
System.out.println("prices[1] = " + BeanUtils.getProperty(bean, "prices[1]"));
Run Code Online (Sandbox Code Playgroud)

输出是:

prices[0] = null
prices[1] = 456
Run Code Online (Sandbox Code Playgroud)

为什么BeanUtils.setProperty()无法设置索引属性,PropertyUtils.setProperty()可以吗?BeanUtils不支持Lists中对象的类型转换吗?

java javabeans apache-commons-beanutils

3
推荐指数
1
解决办法
7007
查看次数

标签 统计

apache-commons-beanutils ×2

java ×2

javabeans ×2

jaxb ×1