Best way to check for null values in Java?

后端 未结 16 1250
傲寒
傲寒 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:20

    If you control the API being called, consider using Guava's Optional class

    More info here. Change your method to return an Optional instead of a Boolean.

    This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional

提交回复
热议问题