How to avoid null checking in Java?

后端 未结 30 3268
失恋的感觉
失恋的感觉 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:32

    Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.

    As explained in the wiki:

    Optional is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."

    Usage:

    Optional possible = Optional.of(5);
    possible.isPresent(); // returns true
    possible.get(); // returns 5
    

提交回复
热议问题