Java: How to check for null pointers efficiently

前端 未结 14 1801
清歌不尽
清歌不尽 2020-12-03 01:17

There are some patterns for checking whether a parameter to a method has been given a null value.

First, the classic one. It is common in self-made code

14条回答
  •  被撕碎了的回忆
    2020-12-03 01:40

    You should not be throwing NullPointerException. If you want a NullPointerException, just dont check the value and it will be thrown automatically when the parameter is null and you attempt to dereference it.

    Check out the apache commons lang Validate and StringUtils classes.
    Validate.notNull(variable) it will throw an IllegalArgumentException if "variable" is null.
    Validate.notEmpty(variable) will throw an IllegalArgumentException if "variable" is empty (null or zero length".
    Perhaps even better:
    String trimmedValue = StringUtils.trimToEmpty(variable) will guarantee that "trimmedValue" is never null. If "variable" is null, "trimmedValue" will be the empty string ("").

提交回复
热议问题