How to avoid null checking in Java?

后端 未结 30 3202
失恋的感觉
失恋的感觉 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条回答
  •  孤街浪徒
    2020-11-21 05:17

    The Google collections framework offers a good and elegant way to achieve the null check.

    There is a method in a library class like this:

    static  T checkNotNull(T e) {
       if (e == null) {
          throw new NullPointerException();
       }
       return e;
    }
    

    And the usage is (with import static):

    ...
    void foo(int a, Person p) {
       if (checkNotNull(p).getAge() > a) {
          ...
       }
       else {
          ...
       }
    }
    ...
    

    Or in your example:

    checkNotNull(someobject).doCalc();
    

提交回复
热议问题