JavaBean中布尔类型使用注意

JavaBean是一个标准,遵循标准的Bean是一个带有属性和getters/setters方法的Java类。

JavaBean的定义很简单,但是还有有一些地方需要注意,例如Bean中含有boolean类型的属性。我们知道对于一个属性来说,如果其命名为test,那么其getter和setter方法一般为getTest()和setTest。但是如果test为一个布尔类型,那么其getter和setter方法为isTest()和setTest()。这是一个区别

public class BeanTest {
    private boolean test;

    public boolean isTest() {
        return test;
    }

    public void setTest(boolean test) {
        this.test = test;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

如果我们将这个属性名换为isTest,那么其生成的getter和setter方法,居然和属性为test时的一样

public class BeanTest1 {
    private boolean isTest;

    public boolean isTest() {
        return isTest;
    }

    public void setTest(boolean test) {
        isTest = test;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这个区别在一般的情况下是没有影响的,但是如果涉及到和json串之间的转换,就得注意了。例如,如果我将上面的两个Bean的对象Json化,其结果居然是一样的

public static void main(String[] args) {
    System.out.println(JSON.toJSONString(new Bean1())); //{"test":false}
    System.out.println(JSON.toJSONString(new Bean2())); //{"test":false}
}
  • 1
  • 2
  • 3
  • 4

如果,我想要生成{“isTest”:false}这样的Json串,那么我们的Bean该怎么定义呢?这时候我们不该依赖于IDEA自动帮我们生成,我们必须手动编写:

public class Bean3{
    private boolean isTest;

    public boolean getIsTest(){
        return isTest;
    }
    public void setIsTest(boolean isTest){
        this.isTest = isTest;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

虽然这样生成了我们想要的json串,但是这样没有遵循Java规范,感觉很别扭。。。。我们可以使用@JSONField来指定json化后对应的字段名

另外,如果属性是boolean的包装类型Boolean,那么JavaBean定义的getter和setter方法又为什么呢?

public class Bean4{
    private Boolean test;

    public Boolean getTest() {
        return test;
    }

    public void setTest(Boolean test) {
        this.test = test;
    }
}

public class Bean5{
    private Boolean isTest;

    public Boolean getTest() {
        return isTest;
    }

    public void setTest(Boolean test) {
        isTest = test;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

我们发现Boolean类型和boolean类型属性的get和set方法也是有差别的。

总的来说,为了避免麻烦,不管是定义Boolean类型的属性,还是定义boolean类型的属性,其字段名不要使用isXXX这种方式,然后按照Bean规范生成get和set方法就好了

猜你喜欢

转载自blog.csdn.net/pf1234321/article/details/78850543
今日推荐