Best way to check for null values in Java?

后端 未结 16 1187
傲寒
傲寒 2020-12-04 16:30

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go abou

16条回答
  •  离开以前
    2020-12-04 17:00

    In Java 8, the best way to check for null is:

    Objects.isNull(obj) //returns true if the object is null
    
    Objects.nonNull(obj) //returns true if object is not-null
    
    if(Objects.nonNull(foo) && foo.something()) // Uses short-circuit as well. No Null-pointer Exceptions are thrown.
    

    Apart from this... You can also go with Guava's Optional Class

提交回复
热议问题