Why should one use Objects.requireNonNull()?

前端 未结 11 1800
谎友^
谎友^ 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 04:56

    Apart from the other answers - to me use of requireNonNull could make a code a bit convenient, (and sometimes easy to read)

    For example - lets examine the code below,

    private int calculateStringLength(String input) {
            return Objects.
                    requireNonNull(input, "input cannot be null").
                    length();
        }
    

    This code returns length of the string passed to it as argument - however it will throw an NPE if input is null.

    As you can see, with use of requireNonNull - there’s no reason to perform null checks manually anymore.

    The other useful thing is the "exception message" is my own hand-written (input cannot be null in this case).

    0 讨论(0)
  • 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<String> 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)

    0 讨论(0)
  • 2020-12-02 05:05

    Fail-fast

    The code should crash as soon as possible. It should not do half of the work and then dereference the null and crash only then leaving half of some work done causing the system to be in an invalid state.

    This is commonly called "fail early" or "fail-fast".

    0 讨论(0)
  • 2020-12-02 05:05

    The basic usage is checking and throwing NullPointerException immediately.

    One better alternative (shortcut) to cater to the same requirement is @NonNull annotation by lombok.

    0 讨论(0)
  • 2020-12-02 05:08

    I think it should be used in copy constructors and some other cases like DI whose input parameter is an object, you should check if the parameter is null. In such circumstances, you can use this static method conveniently.

    0 讨论(0)
提交回复
热议问题