java中null强转Object会出问题吗?

350 阅读1分钟

结论:对于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进行单元测试 www.cnblogs.com/lovesqcc/p/…