Java 杂谈程序员

null强转机制

2018-09-14  本文已影响43人  alonwang

对于Object,null强转是安全的

class LangTest extends Specification {
    def "null cast obj is safe"() {
        when:
        Object a = null
        Integer obj = a
        then:
        obj == null
    }

    def "null cast primitive error"() {
        when:
        Object a = null
        //抛出异常的原因是隐式调用了Integer.intValue(),而a为空
        int primitive = (Integer) a
        then:
        def ex = thrown(NullPointerException)
        ex.class.name == "java.lang.NullPointerException"
    }
}

使用groovy+spock进行单元测试 https://www.cnblogs.com/lovesqcc/p/8647201.html

上一篇下一篇

猜你喜欢

热点阅读