Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeanUtils.setProperty not working for Boolean values?

I have this simple Bean class and try to set some values with BeanUtils.setProperty Problem is, it seems that String works just fine, but when I try to set a Boolean value it just does not work. I have tried and define the field as public but still not working. Any help? Why is this not working?

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        

}

}

like image 615
Ziggurat Avatar asked Jul 04 '12 16:07

Ziggurat


People also ask

How BeanUtils copyProperties works?

BeanUtils class provides a copyProperties method that copies the properties of source object to target object where the property name is same in both objects. Now we will copy the properties of Course object to CourseEntity object: Course course = new Course(); course. setName("Computer Science"); course.

How do you assign a Boolean value in Java?

In Java, there is a variable type for Boolean values: boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false.

What is Commons BeanUtils used for?

Commons BeanUtils is a collection of utilities that makes working with beans and bean properties much easier. This project contains utilities that allow one to retrieve a bean property by name, sort beans by a property, translate beans to maps, and more.

Does BeanUtils use reflection?

As they both ultimately use Reflection you aren't likely to notice much difference, unless the higher-level API is doing things you don't need done. See also java. beans.


1 Answers

You need to change it from

protected Boolean someBoolean;

to

protected boolean someBoolean;

You will get more info from here.

Java Beans, BeanUtils, and the Boolean wrapper class

like image 106
UVM Avatar answered Oct 26 '22 04:10

UVM