BeanUtils.setProperty不适用于布尔值?

时间:2012-07-04 16:38:23

标签: java apache-commons-beanutils

我有这个简单的Bean类并尝试使用BeanUtils.setProperty设置一些值问题是,似乎String工作得很好,但是当我尝试设置一个布尔值时它就不起作用了。我已尝试将该字段定义为公共字段,但仍然无效。有帮助吗?为什么这不起作用?

public class TestBean {

protected Boolean someBoolean;
protected String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public boolean isSomeBoolean() {
    if (someBoolean == null) {
        return true;
    } else {
        return someBoolean;
    }
}

public void setSomeBoolean(Boolean value) {
    this.someBoolean = value;
}

public static void main(String[] args) {
    TestBean o = new TestBean();
    Boolean b = new Boolean(false);
    BeanUtils.setProperty(o, "someBoolean", b);
    BeanUtils.setProperty(o, "name", "A name");
    System.out.println(((TestBean)o).isSomeBoolean());
    // Output = true WHY?????
    System.out.println(((TestBean)o).getName());
    // Output = A name 

    BeanUtils.setProperty(o, "someBoolean", false);
    BeanUtils.setProperty(o, "name", "Another name");

    System.out.println(((TestBean)o).isSomeBoolean());
    // Output = true WHY????
    System.out.println(((TestBean)o).getName());
    // Output = Another name        

}

}

1 个答案:

答案 0 :(得分:3)

您需要从

更改它
protected Boolean someBoolean;

protected boolean someBoolean;

您将从此处获得更多信息。

Java Beans, BeanUtils, and the Boolean wrapper class