You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java字符串校验如何结合isEmpty、isBlank与null检查简化判断逻辑

Java字符串校验条件简化方案

原代码存在的问题

  • 有空指针风险:判断顺序错误,先调用isEmpty()/isBlank()方法再判断!=null,如果字符串为null会直接抛出空指针异常
  • 逻辑冗余:Java 11及以上版本的String.isBlank()已经包含了空字符串的校验逻辑,不需要同时判断isEmpty()和isBlank()
  • 可读性差:所有校验逻辑堆在if条件里,没有语义化,后续维护成本高

优化思路

  1. 抽离公共的字符串有效性校验方法,复用逻辑,避免重复编码
  2. 按业务规则拆分校验条件,用语义化的变量存储条件结果,提升可读性

优化后代码

public class Validate { // 修正类名不符合大驼峰命名规范的问题

    public static void main(String[] args) {
        String productId = "";
        String productItem = "";
        String productName = "Apple";
        String productPrice = "1500";

        // 条件1:productId或productItem存在有效值
        boolean hasValidProductIdentifier = isNonBlank(productId) || isNonBlank(productItem);
        // 条件2:productName和productPrice均包含有效值
        boolean hasValidProductInfo = isNonBlank(productName) && isNonBlank(productPrice);

        if (hasValidProductIdentifier || hasValidProductInfo) {
            System.out.println("valid");
        } else {
            System.out.println("not valid");
        }
    }

    /**
     * 校验字符串是否为非空、非全空白的有效值
     */
    private static boolean isNonBlank(String str) {
        return str != null && !str.isBlank();
    }
}

额外优化提示

如果你的项目已经引入了Apache Commons Lang3或者Spring Core的依赖,可以直接使用现成的工具类方法,不需要自己实现isNonBlank:

  • Apache Commons Lang3:org.apache.commons.lang3.StringUtils.isNotBlank()
  • Spring:org.springframework.util.StringUtils.hasText()
    两个方法的逻辑和上述自定义的isNonBlank完全一致。

内容的提问来源于stack exchange,提问作者Dave Brady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:15:08