常见的判空方式

Posted by Wh0ami-hy on August 10, 2025

常见类型变量的判空方式

字符串(String)

str.isEmpty() 要求 str 不能为 null,否则会抛 NullPointerException

String str = null;

// 方法1:直接判 null 和空字符串
if (str == null || str.isEmpty()) {
    // 为空
}

// 方法2:使用 trim() 忽略空白字符
if (str == null || str.trim().isEmpty()) {
    // 为空或全为空白字符
}

集合(List, Set, Map 等)

推荐的工具类(Apache Commons Lang3)

StringUtils:字符串判空

import org.apache.commons.lang3.StringUtils;

String str = "  ";

// 判断是否为 null、空字符串或仅空白字符
if (StringUtils.isBlank(str)) {
    // 等价于 str == null || str.trim().isEmpty()
}

// 判断是否为 null 或空字符串(不忽略空白)
if (StringUtils.isEmpty(str)) {
    // 等价于 str == null || str.length() == 0
}

CollectionUtils:集合判空

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

List<String> list = null;
Map<String, Object> map = null;

if (CollectionUtils.isEmpty(list)) {
    // list 为 null 或空
}

if (MapUtils.isEmpty(map)) {
    // map 为 null 或空
}

ObjectUtils:对象判空

import org.apache.commons.lang3.ObjectUtils;

if (ObjectUtils.isEmpty(obj)) {
    // obj 为 null 或空集合/数组/字符串等(有限支持)
}

Java 8+ Optional 类(避免 null)

Optional<String> optional = Optional.ofNullable(str);

optional.ifPresent(s -> System.out.println(s));
optional.orElse("default");

本站总访问量