How to check if object is null or not except == null

前端 未结 1 840
广开言路
广开言路 2021-02-09 07:41

I want to make method that will check if the class instance is null or not.

Simply I know that i can use == null, but I want to know that is there any other

相关标签:
1条回答
  • 2021-02-09 07:49

    The easiest way to check is entity == null. There is no shorter way to do that.

    Note that there is a method for this in the standard lib:

    Objects.isNull(Object obj)

    And another one which is the opposite of the above one:

    Objects.nonNull(Object obj)

    And there is yet another one which can be used to force a value to be not null, it throws a NullPointerException otherwise:

    T Objects.requireNonNull(T obj);

    Note: The Objects class was added in Java 7, but the isNull() and nonNull() methods were added only in Java 8.

    0 讨论(0)
提交回复
热议问题