A JavaBean is a standard, and a standards-compliant Bean is a Java class with properties and getters/ Setters methods.
The definition of Javabeans is simple, but there are a few things to be aware of, such as beans containing Boolean type properties. We know that for a property named test, the getter and setter methods are generally getTest() and setTest. But if test is a Boolean type, its getters and setters are isTest() and setTest(). That’s a difference
1 public class BeanTest { 2 private boolean test; 3 4 public boolean isTest() { 5 return test; 6 } 7 8 public void setTest(boolean test) { 9 this.test = test; 11 10}}Copy the code
If we change the property name to isTest, it generates the same getter and setter methods as if the property were test
1 public class BeanTest1 { 2 private boolean isTest; 3 4 public boolean isTest() { 5 return isTest; 6 } 7 8 public void setTest(boolean test) { 9 isTest = test; 11 10}}Copy the code
This difference doesn’t matter in the general case, but it does when converting to and from JSON strings is involved. For example, if I jsonize the objects of the above two beans, the results are the same
1 public static void main(String[] args) {
2 System.out.println(JSON.toJSONString(new Bean1())); //{"test":false}
3 System.out.println(JSON.toJSONString(new Bean2())); //{"test":false}
4 }
Copy the code
If I wanted to generate Json strings like {” isTest “:false}, how would our Bean be defined? At this time we should not rely on IDEA to automatically generate for us, we must manually write:
1 public class Bean3{ 2 private boolean isTest; 3 4 public boolean getIsTest(){ 5 return isTest; 6 } 7 public void setIsTest(boolean isTest){ 8 this.isTest = isTest; 10 9}}Copy the code
While this generates the JSON string we want, it feels awkward because it doesn’t follow the Java specification… We can use @jsonField to specify the corresponding jsonized field name
Also, if the property is a Boolean wrapper type Boolean, what about the getters and setters methods defined by Javabeans?
1 public class Bean4{ 2 private Boolean test; 3 4 public Boolean getTest() { 5 return test; 6 } 7 8 public void setTest(Boolean test) { 9 this.test = test; 10 } 11 } 12 13 public class Bean5{ 14 private Boolean isTest; 15 16 public Boolean getTest() { 17 return isTest; 18 } 19 20 public void setTest(Boolean test) { 21 isTest = test; 23 22}}Copy the code
We also found differences in get and set methods for Boolean types and Boolean type attributes.
In general, to avoid trouble, do not use isXXX for field names, either for Boolean properties or for Boolean properties, and just generate get and set methods according to the Bean specification