How to avoid null checking in Java?

后端 未结 30 3334
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  猫巷女王i
    2020-11-21 05:27

    Java 7 has a new java.util.Objects utility class on which there is a requireNonNull() method. All this does is throw a NullPointerException if its argument is null, but it cleans up the code a bit. Example:

    Objects.requireNonNull(someObject);
    someObject.doCalc();
    

    The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:

    Parent(Child child) {
       if (child == null) {
          throw new NullPointerException("child");
       }
       this.child = child;
    }
    

    becomes

    Parent(Child child) {
       this.child = Objects.requireNonNull(child, "child");
    }
    

提交回复
热议问题