null强转机制

作者: alonwang | 来源:发表于2018-09-14 09:49 被阅读43次

    对于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

    相关文章

      网友评论

        本文标题:null强转机制

        本文链接:https://www.haomeiwen.com/subject/zlbngftx.html