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
}
}
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With