Why should one use Objects.requireNonNull()?

前端 未结 11 1843
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2020-12-02 04:50

    But NullPointerException will be thrown anyway if a null object is dereferenced. So, why should one do this extra null check and throw NullPointerException?

    It means you detect the problem immediately and reliably.

    Consider:

    • The reference may not be used until later in the method, after your code has already performed some side-effects
    • The reference may not be dereferenced in this method at all
      • It could be passed to completely different code (i.e. cause and error are far apart in code space)
      • It could be used much later (i.e. cause and error are far apart in time)
    • It may be used somewhere that a null reference is valid, but has an unintended effect

    .NET makes this better by separating NullReferenceException ("you dereferenced a null value") from ArgumentNullException ("you shouldn't have passed in null as an argument - and it was for this parameter). I wish Java did the same thing, but even with just a NullPointerException, it's still much easier to fix code if the error is thrown at the earliest point at which it can be detected.

提交回复
热议问题