Java开发中常用的判空方法

1. 对象判空

  • 基本判空
if (object != null) {  
    // 处理非空对象  
}

2. 字符串判空

  • 使用 String 的 isEmpty() 方法

if (string != null && !string.isEmpty()) {  
    // 处理非空字符串  
}
  • 使用 String 的 isBlank() 方法(JDK 11及以上):

if (string != null && !string.isBlank()) {  
    // 处理非空且非空白字符串  
}

3. 集合判空

  • 判空集合(如 List, Set, Map)

if (collection != null && !collection.isEmpty()) {  
    // 处理非空集合  
}
  • 判空 Map

if (map != null && !map.isEmpty()) {  
    // 处理非空 Map  
}

4. 数组判空

  • 判空数组
if (array != null && array.length > 0) {  
    // 处理非空数组  
}

5. Java 8 Optional

  • 使用 Optional
Optional<String> optionalString = Optional.ofNullable(string);  
if (optionalString.isPresent()) {  
    // 处理非空值  
    String value = optionalString.get();  
}

6. Apache Commons Lang

  • 使用 Apache Commons Lang 的 ObjectUtils

if (!ObjectUtils.isEmpty(object)) {  
    // 处理非空对象  
} 
  • 使用 StringUtils

if (StringUtils.isNotEmpty(string)) {  
    // 处理非空字符串  
}

7. Guava

  • 使用 Guava 的 Strings
if (!Strings.isNullOrEmpty(string)) {  
    // 处理非空字符串  
}

8. 自定义工具类

  • 自定义判空工具类
public static class Validator {  
    public static boolean isEmpty(Object obj) {  
        if (obj == null) return true;  
        if (obj instanceof String) return ((String) obj).isEmpty();  
        if (obj instanceof Collection) return ((Collection<?>) obj).isEmpty();  
        if (obj instanceof Map) return ((Map<?, ?>) obj).isEmpty();  
        if (obj.getClass().isArray()) return Array.getLength(obj) == 0;  
        return false;  
    }  
}

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值