Why should one use Objects.requireNonNull()?

前端 未结 11 1814
谎友^
谎友^ 2020-12-02 04:06

I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object

11条回答
  •  借酒劲吻你
    2020-12-02 05:02

    As a side note, this fail fast before Object#requireNotNull was implemented slightly different before java-9 inside some of the jre classes themselves. Suppose the case :

     Consumer consumer = System.out::println;
    

    In java-8 this compiles as (only the relevant parts)

    getstatic Field java/lang/System.out
    invokevirtual java/lang/Object.getClass
    

    Basically an operation as : yourReference.getClass - which would fail if yourRefercence is null.

    Things have changed in jdk-9 where the same code compiles as

    getstatic Field java/lang/System.out
    invokestatic java/util/Objects.requireNonNull
    

    Or basically Objects.requireNotNull (yourReference)

提交回复
热议问题